考虑
#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
(这符合我的直觉,但不符合我对标准的理解)。我的理解不正确吗?我错过了什么?
最佳答案
让我们看看我是否可以为此辩护。
上面链接指向的段落说:
- 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/