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.
}
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With