關於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 編譯確實報錯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM