【问题标题】:Declaring array with const and constexpr [duplicate]用 const 和 constexpr 声明数组
【发布时间】:2023-04-08 14:02:02
【问题描述】:

在研究 C++ 中的 constexpr 关键字时,我想出了以下代码:

#include <iostream>

int main() {
    const int n  = 10;
    constexpr int n2 = 10;

    int a1[n];
    int a2[n2];

    std::cout << "n " << n << std::endl;
    std::cout << "n2 " << n2 << std::endl;
}

我希望用“const”声明数组 a1 不起作用,编译器至少会给我一个警告(假设编译是用 g++ -Wall -pedantic constexpr_1.cpp -o ce1 完成的)但它确实不是。我在 VS 编译器中看到了一些错误,所以这里欢迎任何提示。

【问题讨论】:

  • 数组的大小必须在编译时知道,nn2 在编译时是已知的,不能在运行时修改,至少不能以合法的方式修改。也许this question 对你来说很有趣。

标签: c++ constants constexpr


【解决方案1】:

在 C++ 中,数组声明中每个数组维度的大小必须是 integral constant expression

常量表达式(有一些例外)是一个可以在编译时计算的值。这包括具有自动存储持续时间的 const 变量,由常量表达式 [ref] 初始化。

因此const int n = 10;constexpr int n2 = 10; 都可以用作数组声明中的大小,并且代码示例是有效的。

注意:在 C 中不是这种情况 - 所以请确保在 C++ 模式下编译 [ref]

该代码在 MSVC 2015+ 中也可以正常编译。但很可能是一个古老的 VC++ 编译器存在一个错误,导致无法编译。

【讨论】:

  • 好的,谢谢您的回答。我被这篇文章弄糊涂了:smartbear.com/blog/develop/…,它指出编译器应该发出类似这样的警告://编译错误:“需要常量表达式”。
猜你喜欢
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多