gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:15:49 25 4
gpt4 key购买 nike

由于 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 anextension GCC accepts them in C90 mode and in C++.

clang documentation too follows suit but clearly mentioned that the standard doesn't accept (emphasis mine)

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

如果你不想使用这个扩展,你可以随时禁用它-Werror=vla 禁止编译。

关于c++ - 如果创建可变长度数组并使用 g++ 编译会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67201027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com