8

I had always thought that variable length arrays were not allowed in c++(Refer :Why aren't variable-length arrays part of the C++ standard?) .But than why does this code compile and work?

#include <iostream>
using namespace std;

int main () {

    int n;
    cin >> n;

    int a[n];

    for (int i=0; i<n; i++) {
        a[i] = i;
    }

    for (int i=0; i<n; i++) {
        cout << a[i] << endl;
    }
}
4

2 回答 2

7

当前的 C++ 标准不要求编译器支持 VLA。但是,允许编译器供应商支持 VLA 作为扩展。例如,GCC >= 4.7 可以。

最初提议 VLA 将出现在 C++14 中,但该提议没有成功。它们最终也没有出现在 C++17 中。

于 2014-02-25T12:00:16.050 回答
3

C99 允许 VLA,但 C++ 绝不允许,因为 VLA 的性能非常不友好。而在 C11 中,VLA 成为可选功能。

之前,据说 VLA 会出现在 C++17 上。但是现在 C++17 发布了,也没有 VLA。(而且好像C++20不会有VLA,最近的文档根本没谈过。)

虽然标准不支持它,但 GNU 编译器支持它作为扩展

于 2018-04-05T05:22:09.093 回答