gpt4 book ai didi

c - 从已设置为 defined() 结果的宏中期望得到什么值?

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:05 26 4
gpt4 key购买 nike

在下面这个非常简单的 C 程序中,预期的编译器错误是什么? gcc 给我 1,而 MSVC 2013 给我 2。

#define foo
#define bar (defined(foo))

#if bar
#error 1
#else
#error 2
#endif

我的问题希望同样简单:

  1. C 规范对 defined() 的值有何规定?我好像不能找到任何谈论将其值设置为另一个的东西宏观。
  2. 我无法控制实际代码,到处都使用“#if bar”。更改#define 以使#if bar 在 MSVC 中按“预期”工作的最简单方法是什么?我唯一能想到的就是扩展它:

.

#ifdef foo
#define bar 1
#else
#define bar 2
#endif

最佳答案

C 规范说:

§6.10.1/1 The expression ... may contain unary operator expressions of the form defined identifier or defined(identifier) which evaluate to 1 if the identifier is currently defined as a macro name (that is, if it is predefined or if it has been the subject of a #define preprocessing directive without an intervening #undef directive with the same subject identifier), 0 if it is not.

§6.10.1/4 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.

(强调我的)然而,宏替换是如何非常复杂的,我认为 MSVC 正在将 foo 定义为 defined(bar) 这是未定义的行为,而 GCC 正在定义 foo1 正确。由于 MSVC 随后处于未定义行为状态,因此它会做一些奇怪的事情。

正如您所说,最简单的解决方法是

#ifdef foo
#define bar 1
#else
#define bar 2
#endif

关于c - 从已设置为 defined() 结果的宏中期望得到什么值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27278596/

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