关于C++数组的大小使用变量

参考:

1. https://www.py4u.net/discuss/108969

2. https://juejin.cn/post/6931366725602508807

 

在一次代码中看到代码里面数组大小用变量,竟然在g++下编译通过,书本上不是说C++ 的数组大小不能用变量的吗,一定要是确定大小

代码如下:

int main() {
        int n;
        std::cin>>n;
        int a[n];
        return 0;
}

g++ -g main.cpp 并没有报错

 

收集到资料如下:

1. C99 支持变化长度数组,但是C++不支持,使用visual studio微软编译器,确实编译报错,说明C++标准不支持变化长度数组

In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you're seeing a G++ extension. 、
Note that Microsoft
's C compiler does not fully support C99; since G++ supports C99 it's easy enough to apply the VLA support to C++ as an extension.

 

C99如何支持变化长度数组见 参考2

2. g++的扩展功能,默认支持vla

These are called variable length arrays (VLA) and are a g++ compiler extension which is not part of the C++ standard. Do not use it in C++ if you want your code to be portable.

You can make g++ emit a warning with the -Wvla compilation flag, or an error with flag -Werror=vla. I usually compile with -pedantic-errors, which catches this and many other deviations from the standard.

使用g++ -g -Werror=vla main.cpp 编译确实报错

 

posted @ 2022-01-04 17:36  蓝天飞翔的白云  阅读(827)  评论(0编辑  收藏  举报