如果创建可变长度数组并使用 g++ 编译会发生什么

what happens if you create a variable length array and compile using g++

由于 g++ 允许,以下代码可以正常编译,但它会导致未定义的行为吗?或者我的代码可以正常工作?如果在使用时不产生错误,C++ 标准不允许可变长度数组是什么意思?

#include <iostream>

using namespace std;

int main()
{
   int x;
   cin >> x;
   char abc[x];
   cout << sizeof(abc) << "\n";
   
   return 0;
}

GCC 记录其对 VLA 的支持here强调我的

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++.

CLANG documentation 也效仿但明确提到标准不接受(强调我的

GCC and C99 allow an array's size to be determined at run time. This extension is not permitted in standard C++. However, Clang supports such variable length arrays for compatibility with GNU C and C99 programs.

如果您不想使用此扩展程序,您可以随时将其禁用 -Werror=vla 禁止编译。