- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
给定以下 C 文件:
$ cat macros.c
#ifdef MACRO
# error MACRO is defined
#else
# error MACRO is undefined
#endif
#if MACRO
# error MACRO is non-zero
#else
# error MACRO is zero
#endif
以下的预期输出是什么?
$ gcc -c macros.c
$ gcc -DMACRO -c macros.c
$ gcc -DMACRO=0 -c macros.c
回答:这是我机器上的 gcc 预处理器所做的。
$ gcc -c macros.c
macros.c:4:4: error: #error MACRO is undefined
macros.c:9:4: error: #error MACRO is zero
$ gcc -DMACRO -c macros.c
macros.c:2:4: error: #error MACRO is defined
macros.c:7:4: error: #error MACRO is non-zero
$ gcc -DMACRO=0 -c macros.c
macros.c:2:4: error: #error MACRO is defined
macros.c:9:4: error: #error MACRO is zero
$
类(class):#ifdef MACRO
对已定义的计算结果为真,即使定义的值为 0(零)。
另一个 C 预处理器陷阱!按照 C 标准,这应该是这样吗?
最佳答案
为了评估 #if
语句的控制表达式,任何未定义的宏都被视为定义为 0。来自 C99 §6.10.1/3-4(添加了重点):
3) Preprocessing directives of the forms
# if constant-expression new-line group
opt
# elif constant-expression new-line group
opt
check whether the controlling constant expression evaluates to nonzero.
4) Prior to evaluation, macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the
defined
unary operator), just as in normal text. If the tokendefined
is generated as a result of this replacement process or use of thedefined
unary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined. After all replacements due to macro expansion and thedefined
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. [...]
因此,例如,这样的表达式:
#if !FOO
如果 FOO
未定义,将评估为 1
,因为它将被视为 0,然后 !FOO
将评估为!0
,即 1
。
关于c - 对于定义为 0 的宏,#ifdef 和 #if 之间的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21312617/
我是一名优秀的程序员,十分优秀!