问题
I have such a code in C
enum {
MYVAR = 1
};
#ifdef MYVAR
#define VAR 1
#else
#define VAR 2
#endif
printf("VAR = %d", VAR);
in this case it will prints "VAR = 2".
Is there any way to get preprocessor see the definition in enum?
回答1:
No, this is not possible. #ifdef and #if are part of preprocessor, which completes its run before the portion of the compiler that "understands" enums.
#ifdef works only with preprocessor constants (i.e. things defined with #define, or passed to the compiler on the command line, say, with a -DMYVAR=123 option).
#if works with integer and character constants, and preprocessor constants. All identifiers which are not preprocessor constants are considered undefined, and interpreted as if they were zeros when evaluating #if conditions. This includes enum constants.
来源:https://stackoverflow.com/questions/21073867/constant-in-enum-not-seen-in-define