tags:

views:

163

answers:

3

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!

+4  A: 

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

Kirill V. Lyadvinsky
+2  A: 

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
+4  A: 

Macros cannot alter the preprocessing environment, but headers can.

#define MEMORIZE hello
#include <memorize.h>

/* code block */

READ_FOO // expands to hello

/* more code */

#define MEMORIZE world
#include <memorize.h>

READ_FOO // expands to world

memorize.h:

#undef READ_FOO
#ifndef MEMORIZE
#   error "No argument to memorize.h"
#endif
#define READ_FOO MEMORIZE
#undef MEMORIZE
Potatoswatter
Of course that would mean that the header does not contain header guards...
Matthieu M.
But that's ok as long as it `#undef` s READ_FOO.
Joe D