编程参考 - C语言中未定义宏的值

在C99和C++11标准中,未定义的宏在条件编译中会被替换为0。pp-number是指预处理过程中的数值表示,用于描述数字和计数法。当在预处理指令#if中使用未定义的宏时,代码可以正常编译并将其视为0;而在代码中直接使用未定义的宏会导致编译错误。
摘要由CSDN通过智能技术生成

在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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜流冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值