Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redefine a C++ #define macro using information from the macro itself?

Is it possible to redefine a C++ #define macro using information from the macro itself? I tried the code below, but because of the way the macros are evaluated the output was not what I expected.

#include <iostream>

#define FINAL_DEFINE "ABC"
#define NEW_DEFINE FINAL_DEFINE "DEF" // Want ABCDEF

#undef FINAL_DEFINE
#define FINAL_DEFINE NEW_DEFINE // Want ABCDEF, but get empty?


int main ()
{
    std::cout << FINAL_DEFINE << std::endl; // Want ABCDEF, but doesn't compile.
}
like image 464
Jeff Avatar asked Apr 20 '16 05:04

Jeff


People also ask

Can I redefine a variable in C?

In C, you cannot redefine an existing variable. For example, if int my_var = 2 is the first definition, your program won't compile successfully if you try redefining my_var as int my_var = 3 . However, you can always reassign values of a variable.

Can you redefine a variable?

In most functional languages, when you define a variable with the same name as an existing variable, the new definition shadows the old definition but will not affect any previous references to the old variable.

Can we redefine a macro in C?

A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive. Here's an example. Here, when we use c in our program, it is replaced with 299792458 .


1 Answers

Macros in macro bodies are never expanded when the macro is defined -- only when the macro is used. That means that the definition of NEW_DEFINE is not "ABC" "DEF", it is exactly what appears on the #define line: FINAL_DEFINE "DEF".

So when you use FINAL_DEFINE, that gets expanded to NEW_DEFINE which then gets expanded to FINAL_DEFINE "DEF". At this point it will not recursively expand FINAL_DEFINE (as that would lead to an infinite loop) so no more expansion occurs.

like image 161
Chris Dodd Avatar answered Sep 25 '22 03:09

Chris Dodd