Reputation: 1335
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.
}
Upvotes: 6
Views: 963
Reputation: 126203
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.
Upvotes: 3
Reputation: 9260
If your compiler supports push_macro
& pop_macro
pragma directives, you could do this:
#include <iostream>
#define FINAL_DEFINE "ABC"
#define NEW_DEFINE FINAL_DEFINE "DEF"
int main ()
{
std::cout << FINAL_DEFINE << std::endl; // Output ABC
#pragma push_macro("FINAL_DEFINE")
#define FINAL_DEFINE "XXX"
std::cout << NEW_DEFINE << std::endl; // Output XXXDEF
#pragma pop_macro("FINAL_DEFINE")
}
Upvotes: 2
Reputation: 6103
After preprocessing all FINAL_DEFINE
in the code will be replaced with the last thing it defined and then going to compiling step.
So you cannot redefine the macro like you want.
Your compiler should warn you about that.
Upvotes: 0