Why does the C preprocessor consider enum values as equal?

后端 未结 7 1257
南方客
南方客 2020-12-08 12:48

Why does the std::cout line in the following code run even though A and B are different?

#include 

en         


        
相关标签:
7条回答
  • 2020-12-08 13:44

    As the other answers said, the C preprocessor doesn't see enums. It expects, and can only understand, macros.

    Per the C99 standard, §6.10.1 (Conditional inclusion):

    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

    In other words, in an #if or #elif directive, any macros that cannot be expanded, because they don't exist/are undefined, will behave exactly as if they'd been defined as 0, and therefore will always be equal to each other.

    You can catch likely unintended behavior like this in GCC/clang with the warning option -Wundef (you'll probably want to make it fatal with -Werror=undef).

    0 讨论(0)
提交回复
热议问题