gpt4 book ai didi

c - 对于定义为 0 的宏,#ifdef 和 #if 之间的细微差别

转载 作者:太空狗 更新时间:2023-10-29 17:17:16 27 4
gpt4 key购买 nike

给定以下 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 groupopt
# elif constant-expression new-line groupopt

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 token defined is generated as a result of this replacement process or use of the defined 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 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. [...]

因此,例如,这样的表达式:

#if !FOO

如果 FOO 未定义,将评估为 1,因为它将被视为 0,然后 !FOO 将评估为!0,即 1

关于c - 对于定义为 0 的宏,#ifdef 和 #if 之间的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21312617/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com