引用以下代码段:
int main() {
const std::size_t tabsize = 50;
int tab[tabsize]; // OK: tabsize is a constant expression
std::size_t n = 50;
const std::size_t sz = n;
int tab2[sz]; // error: sz is not a constant expression
// because sz is not initialized with a constant expression
}
当我使用 (gcc 4.2) 编译上面的代码段时:
g++ -ggdb -pedantic -std=c++14 -Wall
对于代码中突出显示为错误的行,只会生成以下警告:
warning: variable length arrays are a C99 feature
[-Wvla-extension]
int tab2[sz]; // error: sz is not a constant expression
^
这似乎与上述链接中概述的要求相矛盾,即核心常量表达式不得评估左值->右值隐式转换,除非值:
has integral or enumeration type and refers to a complete non-volatile const object, which is initialized with a constant expression
感谢您的想法。
最佳答案
支持可变长度数组是一种编译器扩展,标准通常允许这种扩展,只要它不会使一致的代码表现不同,并且只要它们说它是一种扩展( GCC 会处理该警告):
A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this document. Having done so, however, they can compile and execute such programs.
如果需要,您可以通过 -pedantic-errors
禁用所有扩展。
关于c++ - 核心常量表达式和数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440758/