首页 > 解决方案 > c++ 在函数中获取 const 的可变大小堆栈数组

问题描述

我现在正在学习 C++ 我正在阅读 Effective C++ (Scott Meyers) 一书。在书中,有一个关于 const 变量的项目,我尝试使用它们。我注意到一些非常有趣的事情,如果它在 C++ 中出现错误,我应该知道什么:(我正在使用 C++98 标准)

void Test(const int i)
{
    int arr[i] = {0};
    
    for (int j = 0; i > j; ++j)
    {
        arr[j] = i;
    }
}

这个函数将完全按照我的意愿编译和工作(在堆栈上创建大小为“i”的 int 数组。当我从“i”中删除“const”时,它不会编译。我在 gcc 和 clang 上尝试了这个。

编辑:链接到编译器资源管理器

标签: c++arraysconstants

解决方案


为了在将来发现这种错误,您想要 g++ 和 clang++ 的编译器标志是-pedantic. 并且永远记得指定你的语言标准,否则你不知道你会得到什么。

$ g++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp: In function ‘void f(size_t)’:
c++-vla.cpp:3:30: warning: ISO C++ forbids variable length array ‘g’ [-Wvla]
    3 | void f(const size_t x) { int g[x]; }
      |                              ^

$ clang++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla
c++-vla.cpp:3:31: warning: variable length arrays are a C99 feature [-Wvla-extension]
void f(const size_t x) { int g[x]; }
                              ^
1 warning generated.

推荐阅读