A token that looks like a preprocessing directive should not be used as a macro argument. Using preprocessing directives as macro arguments results in undefined behavior.
Look at the example:
#include <stdio.h
#define PRINT(arg) printf("%s", #arg)
int main(int argc, char *argv[])
{
PRINT(My program prints:
#ifndef FLAG
hello.
#else
world.
#endif
);
}
Depending on whether the FLAG macro is defined, the developer expects the program to print either My program prints: hello or My program prints: world to stdout. Because the behavior is undefined, the compiler can do anything in this situation.
If a program is compiled using GCC or Clang without defining the FLAG macro, the result will be one of the expected options:
My program prints: hello.
However, a program compiled using MSVC will print an unexpected result:
My program prints: #ifndef FLAG hello. #else world. #endif
The fixed code:
#include <stdio.h>
#define PRINT(arg) printf("%s", #arg)
int main(int argc, char *argv[])
{
#ifndef FLAG
PRINT(My program prints: hello.);
#else
PRINT(My program prints: world.);
#endif
}
Now all programs compiled using different compilers print the same text depending on the FLAG macro definition.
Was this page helpful?
Your message has been sent. We will email you at
If you do not see the email in your inbox, please check if it is filtered to one of the following folders: