gpt4 book ai didi

C 预处理器 : what is the motivation behind treating undefined macro as 0?

转载 作者:行者123 更新时间:2023-12-03 23:58:48 26 4
gpt4 key购买 nike

ISO/IEC 9899:202x (E) 工作草案 - 2020 年 2 月 5 日 C17..C2x N2479:

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.

换句话说:

An identifier that is not defined as a macro is converted to 0 before the expression is evaluated.

这导致 UNDEFINED == 0 为真:

#if UNDEFINED == 0
#pragma message "UNDEFINED == 0 is true"
#endif
$ gcc t0.c -E
t0.c:3:9: note: '#pragma message: UNDEFINED == 0 is true'

但是,如何在概念上(逻辑上、数学上、哲学上等)UNDEFINED 等于 0(导致 UNDEFINED == 0true) 吗?

例如,在 IEEE 754 中,NaN 可以被视为 UNDEFINED(不是数字,因此,没有数字,数字未定义,即未定义) 和 NaN == 0false:

#include <stdio.h>
#include <math.h>
int main( void )
{
printf("NaN == 0 is %d\n", NAN == 0);
return 0;
}
$ gcc t0.c && ./a.exe
NaN == 0 is 0

问题:在 C 预处理器中将未定义宏视为 0 的动机是什么?

最佳答案

Question: What is the motivation behind treating in C preprocessor undefined macro as 0?

强调预处理器。预处理器将未定义的宏视为0,但编译器不将其视为0。比如下面的编译失败:

#undef UNDEFINED
#if UNDEFINED == 0 // ok, preprocessor evaluates this as '0 == 0'
int n = UNDEFINED; // error, compiler sees this as 'int n = <undeclared-identifier>;'
#endif

与其他特质一样,“为什么”问题的真正答案是“因为 C 语言标准是这样说的”。虽然很难追查几十年前的原始动机,但这种行为实际上确实简化了某些结构,例如以下足以检查 C99 合规性,而不必担心 standard macro __STDC_VERSION__ 是否由实现定义:

#if __STDC_VERSION__ >= 199901L
// safely assume C99 or later
#else
// either __STDC_VERSION__ is not defined
// or it is earlier than C99
#endif

关于C 预处理器 : what is the motivation behind treating undefined macro as 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65745333/

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