c++ - 在 C++20 中,如果宏是 #undef'd,然后又是 #define'd,那么它是否被认为是 "active"?

标签 c++ language-lawyer c++20

考虑

#define VER 1
#undef VER
#define VER 2

#if defined(VER) // #1
#error VER is defined 
#endif
[cpp.import]/6 :

A macro directive is active at a source location if it has a point of definition in that translation unit preceding the location, and does not have a point of undefinition in that translation unit preceding the location.


我的理解是VER#1 之前有一个未定义点(#undef VER),因此它不被认为是活跃的。即,defined(VER)应该扩展到 0 ,以及 #error指令不应生效。
但实际上,所有编译器都会产生一个错误,说 VER is defined (这符合我的直觉,但不符合我对标准的理解)。
我的理解不正确吗?我错过了什么?

最佳答案

让我们看看我是否可以为此辩护。
上面链接指向的段落说:

  1. Each #define directive encountered when preprocessing each translation unit in a program results in a distinct macro definition.

所以,#define VER 1是一个定义,而 #define VER 2是一个独特的。

5.1 The point of definition of a macro definition within a translation unit is the point at which its #define directive occurs


显然,两者都有一个定义点。

5.2 The point of undefinition of a macro definition within a translation unit is the first point at which a #undef directive naming the macro occurs after its point of definition, [...]


#define VER 1有一点不确定,而#define VER 2没有。
因此,#define VER 2的宏定义在测试位置处于事件状态。在更早的时候,#define VER 1反而会活跃。

再说一次,如果你要这样做:
#define X 1
#define X 2
#undef X

/* is X active now ??? */
第一个 #define 似乎没有“不确定点” ,但我认为你会遇到

7 If a macro would be replaced or redefined, and multiple macro definitions are active for that macro name, the active macro definitions shall all be valid redefinitions of the same macro


因为它们不是同一个宏。 (在 cpp.replace 页面中有示例。)虽然 GCC 和 Clang 接受了警告,但明显的语义是用新值重新定义它(而不是例如堆叠定义以便 #undef 只会删除一个 -那种方式就是疯狂。)

关于c++ - 在 C++20 中,如果宏是 #undef'd,然后又是 #define'd,那么它是否被认为是 "active"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66366900/

相关文章:

c++ - 在 OpenGL 中动态加载着色器毫无意义吗?

c++ - 空洞的大小是多少?

c++ - 错误 : no viable overloading with clang, 用 gcc 编译

c++ - rethrow_exception 真的可以抛出相同的异常对象,而不是一个拷贝吗?

c++ - 什么时候在编译时计算range::views?

c++ - 为什么数组访问和指针算术不等同于完全优化?

c++ - 如何从 Windows 快捷方式(.lnk 文件)以编程方式 (C++) 启动应用程序?

c++ - 如果我在 x86_64 上使用 gcc 4.9,__float128 到底是什么?

c++ - 字符大小困惑

c++ - 在 c++20 中删除了默认构造函数的聚合初始化