c++ - 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 上尝试了这个。
编辑:链接到编译器资源管理器
解决方案
为了在将来发现这种错误,您想要 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.
推荐阅读
- javascript - 实施引导程序后的路由错误
- sql - 如何将用户(名称,密码,角色,订阅)等数据加密为令牌并将其放入数据库中的一个单元格
- mesh - 在 fipy 中通过 Gmsh 导入 3D 网格时出现问题
- firebase - 当您知道字段值时,删除 firebase 中的文档
- python - 如何格式化我的文本数据集以进行训练?
- amazon-web-services - AWS execute-api 端点请求超时/拨号 tcp i/o 超时
- python - 神经网络架构推荐
- css - 如何使用 Material UI 和 Flexbox 使播放按钮居中
- powershell - 使用 Powershell 的两个 .csv 文件之间的区别
- c - 在英文 ASCII 字符中转换十六进制数字