c++ - 为什么全局数组大小应该是整数常量?

标签 c++ variable-length-array

在 C++ 中,我尝试声明某个大小的全局数组。我得到了错误:

array bound is not an integer constant before ‘]’ token



但是当我在 main() 中声明了一个相同类型的数组时功能它工作正常。

为什么这里有不同的行为?
int y=5;
int arr[y];         //When I comment this line it works fine

int main()
{
    int x=5;
    int arr2[x];        // This line doesn't show any error.
}

编辑:许多人认为这个问题与 Getting error "array bound is not an integer constant before ']' token" 重复.但是这个问题并没有回答为什么会有不同的行为。

最佳答案

这两个示例在 C++ 中都是格式错误的。如果编译器不诊断后者,则它不符合标准。

Why there is a different behaviour here?



您使用允许运行时长度自动数组的语言扩展。但不允许运行时长度静态数组。全局数组具有静态存储。

如果您使用 GCC,您可以使用 -pedantic 命令行选项要求它符合标准。这样做是一个好主意,以便了解可移植性问题。

关于c++ - 为什么全局数组大小应该是整数常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60620769/

相关文章:

c++ - QueryPerformanceCounter函数在在线判断中的使用

c - 带有可变长度数组的奇怪输出?

c++ - 为什么我的 C++ 程序的内存使用量不断增长?

c - 动态分配内存有必要用new吗?

C编译错误: "Variable-sized object may not be initialized"

c++ - 如何将 Visual Studio 用作可变长度数组 (VLA) 工作的 IDE?

c - VLA 和通过 malloc 进行动态内存分配有什么区别?

c++ - WINAPI - 在不成为所有者的情况下关闭互斥锁

c++ - 为什么 ifstream 没有读到最后?

c++ - 英特尔引脚 : correctly continuing execution after RECEIVED_ACCESS_FAULT exception