在C99标准中,可以查看到说明:
在6. Language -> 6.10 Preprocessing directives -> 6.10.1 Conditional inclusion里,第4点:
After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token.
在C++11标准中,也可以查看到说明:
在16. Preprocessing directives -> 16.1 Conditional inclusion里,第4点:
After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords146, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token.
就是说,没有定义的宏,会转换为0值。
关于pp-number:
在C99标准中,6. Language -> 6.4 Lexical elements -> 6.4.8 Preprocessing numbers里,
pp-number:
digit
. digit
pp-number digit
pp-number identifier-nondigit
pp-number e sign
pp-number E sign
pp-number p sign
pp-number P sign
pp-number .
pp-number指的是预处理过程中的数字符号。可以是数字开头,或小数点开头。可以使用计数法,比如使用e+, e-, E+, E-, p+, p-, P+ 或P-的字符序列,对应相应的计数方法。
关于解析过程
宏定义在预处理阶段展开,如果没有定义,在预处理命令中使用此宏,则此宏的值为0;在普通代码中展开此宏的话,会出现编译错误。例子如下:
未定义的宏的值为0:
#include <stdio.h>
int main()
{
#if VALUE == 0
printf("hello\n");
#endif
printf("goodbye!\n");
return 0;
}
$ g++ -o testMacro testMacro.cpp
$ ./testMacro
hello
goodbye!
如果在代码中使用未定义宏会编译出错:
#include <stdio.h>
int main()
{
#if VALUE == 0
int abc = VALUE;
printf("hello\n");
#endif
printf("goodbye!\n");
return 0;
}
$ g++ -o testMacro testMacro.cpp
testMacro.cpp: In function ‘int main()’:
testMacro.cpp:7:11: error: ‘VALUE’ was not declared in this scope
7 | int abc = VALUE;
| ^~~~~
参考:
1,c++ - What is the value of an undefined constant used in #if? - Stack Overflow