c++ - 核心常量表达式和数组索引

标签 c++ constant-expression

引用以下代码段:

Core constant expressions

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.

[intro.compliance]/8

如果需要,您可以通过 -pedantic-errors 禁用所有扩展。

关于c++ - 核心常量表达式和数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440758/

相关文章:

c++ - 在 printf 上输出

c++ - 如何在函数中分配指向新对象的指针,而该对象在编辑后不会消失

c++ - 为什么 MFC 中的模式对话框实际上在内部是无模式的?

c++ - switch-case 标签中的 C11 和常量表达式求值

c - 如何避免 if 上出现 "constant expression"?

c++ - 在 C++ 中使用私有(private)继承时是否可以隐藏重载方法

c++ - 常量变量与常量引用

c++ - 可以在编译时对数组进行索引吗?

string - 带有三元运算符的 Java SE 11 字符串最终变量在 Switch Case 表达式中不算作常量变量

c++ - 对 3X3 或 4X4 行列式进行单元测试