在 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/