What is the value of an undefined constant used in #if?

喜你入骨 提交于 2019-12-17 02:49:08

问题


My preprocessor appears to assume that undefined constants are 0 for the purpose of evaluating #if conditions.

Can this be relied upon, or do undefined constants give undefined behaviour?


回答1:


Yes, it can be relied upon. The C99 standard specifies at §6.10.1 ¶3:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers are replaced with the pp-number 0

Edit

Sorry, I thought it was a C question; still, no big deal, the equivalent section in the C++ standard (§16.1 ¶4) states:

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers and keywords, except for true and false, are replaced with the pp-number 0

The only difference is the different handling of true and false, which in C do not need special handling, while in C++ they have a special meaning even in the preprocessing phase.




回答2:


An identifier that is not defined as a macro is converted to 0 before the expression is evaluated.

The exception is the identifier true, which is converted to 1. This is specific to the C++ preprocessor; in C, this doesn't happen and you would need to include <stdbool.h> to use true this way, in which case it will be defined as a macro and no special handling is required.



来源:https://stackoverflow.com/questions/5085392/what-is-the-value-of-an-undefined-constant-used-in-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!