c++ - 在预处理器条件中使用 bool 文字是否有效?

标签 c++ c-preprocessor language-lawyer

考虑以下代码,它导致 bool 文字 true 在预处理器条件中被评估:

#define SOME_MACRO true

int main ()
{
#if SOME_MACRO
  return 1;
#else
  return 0;
#endif
}

Clang 3.4 和 GCC 4.8 都接受此代码,即使使用 -pedantic -std=c++11 -Wall -Wextra

Visual Studio 2013 以 fatal error C1017: invalid integer constant expression 拒绝它.

我对 n3376 的阅读§ 16.1 是应该应用评估常量表达式的常规 C++ 规则。

如果是这样,这段代码是有效的,如果 MSVC 不接受它,它就是一个错误。

但我觉得标准不是特别清楚。有人可以证实这一点吗?

最佳答案

是的,它是有效的。参见 C++11 §16.1/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 and keywords, except for true and false, are replaced with the pp-number 0, and then each preprocessing token is converted into a token. The resulting tokens comprise the controlling constant expression which is evaluated according to the rules of 5.19 using arithmetic that has at least the ranges specified in 18.3. For the purposes of this token conversion and evaluation all signed and unsigned integer types act as if they have the same representation as, respectively, intmax_t or uintmax_t (18.4). This includes interpreting character literals, which may involve converting escape sequences into execution character set members. Whether the numeric value for these character literals matches the value obtained when an identical character literal occurs in an expression (other than within a #if or #elif directive) is implementation-defined. Also, whether a single-character character literal may have a negative value is implementation-defined. Each subexpression with type bool is subjected to integral promotion before processing continues.

关于c++ - 在预处理器条件中使用 bool 文字是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23986834/

相关文章:

c++ - 递归快速排序导致段错误(不是溢出)

c - 在多级宏调用中将宏参数字符串化

c++ - 对象初始化中是否允许指向 this 成员的指针?

c++ - 使用按位运算符和 bool 逻辑的绝对值 abs(x)

c++ - 在 std 命名空间中添加模板特化

c++ - 如何在源文件中对模板函数进行专门化?

c++ - 如何使用 SDL2 为每个线程设置一个共享的 OpenGL 上下文?

c++ - #include <winsqlite/winsqlite3.h> 在一个项目中工作,而不在另一个项目中工作

c - 当我在.h中使用预处理#warning时如何避免来自gcc的多重警告

C++,使用#if TRUE 条件指令