【发布时间】:2019-06-22 18:12:24
【问题描述】:
为什么下面的代码不能编译?
// source.cpp
int main()
{
constexpr bool result = (0 == ("abcde"+1));
}
编译命令:
$ g++ -std=c++14 -c source.cpp
输出:
source.cpp: In function ‘int main()’:
source.cpp:4:32: error: ‘((((const char*)"abcde") + 1u) == 0u)’ is not a constant expression
constexpr bool result = (0 == ("abcde"+1));
~~~^~~~~~~~~~~~~~~
我正在使用 gcc6.4。
【问题讨论】:
-
哦,真的吗?现在我很困惑......这应该做什么? Afaik 你永远无法通过向指针添加内容获得
0 -
GCC 7.x 及更高版本编译您的代码没有任何错误(带有
-std=c++14 -pedantic-errors标志)。 Clang 和 MSVC 也没有抱怨。可能是 GCC 6 错误? -
@user463035818 当然表达式是
false,OP 不反对。问题是为什么它不能编译。 -
godbolt.org/z/oYNZIQ 重现错误。如果将
"abcd"替换为&"abcd"[0],它可以工作(甚至是内联的)。无论出于何种原因,const char[]->const char*衰减似乎都不算作constexpr。
标签: c++ gcc c++14 language-lawyer constexpr