加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:59:13 所属栏目:百科 来源:网络整理
导读:给出下面的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
给出下面的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
$

课程:#ifdef即使定义的值为0(零),MACRO也会对定义的内容求值为true.

另一个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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读