Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ macros with memory?

Tags:

c++

macros

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!

like image 516
anon Avatar asked Mar 24 '10 08:03

anon


People also ask

Do macros use memory?

No, Macro does not allocate the memory. These statements are not like variable assignment, no memory is allocated.

Does macro uses stack memory?

Explanation: Macro does not require stack memory and hence has less time for execution.

Are macros faster than functions C?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it's used. A function definition occurs only once regardless of how many times it's called.

Where are macro variables stored?

Macro variables are stored in symbol tables, which list the macro variable name and its value. There is a global symbol table, which stores all global macro variables. Local macro variables are stored in a local symbol table that is created at the beginning of the execution of a macro.


3 Answers

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.

like image 80
Potatoswatter Avatar answered Sep 23 '22 04:09

Potatoswatter


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

like image 21
Kirill V. Lyadvinsky Avatar answered Sep 22 '22 04:09

Kirill V. Lyadvinsky


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;
like image 30
David Rodríguez - dribeas Avatar answered Sep 21 '22 04:09

David Rodríguez - dribeas