gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:23:23 26 4
gpt4 key购买 nike

考虑以下代码,它导致 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/

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