是否应该定义#if 中使用的宏?
Should a macro used in #if be defined?
# if RTC
/* some code */
# endif
宏RTC
是否应该定义一个值?我的编译器没有抛出错误。所有的编译器都这样做吗?定义宏不是更安全吗?
在这样的预处理指令中,如果宏未定义,则将其视为0
。
这是语言保证的。
你可以相信没有编译失败。
这是 C++ 的措辞:
[cpp.cond]/11
: After all replacements due to macro expansion and evaluations of defined-macro-expressions, has-include-expressions, and has-attribute-expressions have been performed, all remaining identifiers and keywords, except for true
and false
, are replaced with the pp-number 0
, and then each preprocessing token is converted into a token. [..]
不,不必定义。如果标识符在 #if
扩展末尾未定义,则其计算结果为 0
.
来自 ANSI C90:
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
.
但是,在 C 标准化之前的编译器中可能不存在这种情况。我曾经看到一个关于这个的 GCC 警告(我认为它在 MinGW 上)但是我现在找不到它的来源。
结论:所有符合标准的 C 编译器在遇到此问题时不应抛出错误。在 #if
.
中使用它之前不需要定义宏
# if RTC
/* some code */
# endif
宏RTC
是否应该定义一个值?我的编译器没有抛出错误。所有的编译器都这样做吗?定义宏不是更安全吗?
在这样的预处理指令中,如果宏未定义,则将其视为0
。
这是语言保证的。
你可以相信没有编译失败。
这是 C++ 的措辞:
[cpp.cond]/11
: After all replacements due to macro expansion and evaluations of defined-macro-expressions, has-include-expressions, and has-attribute-expressions have been performed, all remaining identifiers and keywords, except fortrue
andfalse
, are replaced with the pp-number0
, and then each preprocessing token is converted into a token. [..]
不,不必定义。如果标识符在 #if
扩展末尾未定义,则其计算结果为 0
.
来自 ANSI C90:
After all replacements due to macro expansion and the
defined
unary operator have been performed, all remaining identifiers are replaced with the pp-number0
.
但是,在 C 标准化之前的编译器中可能不存在这种情况。我曾经看到一个关于这个的 GCC 警告(我认为它在 MinGW 上)但是我现在找不到它的来源。
结论:所有符合标准的 C 编译器在遇到此问题时不应抛出错误。在 #if
.