7

Is it possible to define macros

write_foo(A);
and
read_foo();

so that:

WRITE_FOO(hello);

code_block_1;

READ_FOO();

code_block_2;

READ_FOO();

WRITE_FOO(world);

code_block_3;

READ_FOO();

code_block_4;

READ_FOO();

expands into:

code_block_1;
hello;
code_block_2;
hello;

code_boock_3;
world;
code_block_4;
world;

?

Thanks!

anon
  • 41,035
  • 53
  • 197
  • 293

4 Answers4

4

It is not possible since macro should not contain preprocessor directives.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
4

Macros cannot redefine other macros, but you can do it manually.

#define FOO hello

FOO // expands to hello

#undef FOO
#define FOO world

FOO // expands to world

#undef FOO
#define FOO blah

FOO // expands to blah

Unfortunately, the #define + #undef combination cannot be encapsulated in any other structure that I am aware of.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • But that's ok as long as it `#undef` s READ_FOO. – Joe D Jul 23 '10 at 09:14
  • Guess what! [Somebody tried this](http://stackoverflow.com/questions/9526096/c-macro-with-memory) and it doesn't work! – Shahbaz Mar 02 '12 at 00:21
  • @Shahbaz: Bah, there's egg on my face — you're right, it doesn't work. I understand the preprocessor better now than I did when I posted this, and I don't think there's any way to fix this or really answer the question. The `#undef` needs to occur after the uses of `READ_FOO` and before the `#define` which resets the parameter. Headers cannot simplify the obvious, straightforward solution simply using `#define` and `#undef` as they were originally intended. – Potatoswatter Mar 02 '12 at 04:13
3

Not what you are actually asking for, but if WRITE_FOO was a definition you could get something similar (without context I will just reuse the names, even if they are not so clear on the intent):

#define READ_FOO() WRITE_FOO

#define WRITE_FOO hello
code...[1]
READ_FOO();
code...[2]
#define WRITE_ROO world
code...[3]
READ_FOO();

// will expand to:
code...[1]
hello;
code...[2]
code...[3]
world;
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
1

this is the sweet spot for tools like Cog that approach the problem of code generation from an intuitive programming approach using python. This is what would look like your code using it

/*[[[cog
# definitions ----
import cog
Foo = ''
def WriteFoo( value ):
    Foo = value

def ReadFoo():
    cog.outl(' %s; ' % Foo)

# generation ---
WriteFoo( 'hello' )
]]]*/
//[[[end]]]

some_code_block;

/*[[[cog 
ReadFoo() ]]]*/
hello;
//[[[end]]]

some_other_blocK;

/*[[[cog 
WriteFoo( 'world')
ReadFoo() ]]]*/
world;
//[[[end]]]


last_block;
lurscher
  • 25,930
  • 29
  • 122
  • 185