我正在尝试做这样的事情:
const int array_size = 5;
string stuff[array_size];
我的编译器不允许我编译它,即使 array_size
是一个常量。有没有办法在不处理动态数组的情况下做到这一点?
编辑:“错误 C2057:预期的常量表达式”
最佳答案
I have answered this question assuming you are either coding in C or C++. If you are using a different language, this answer doesn't apply. However, you should update your question with the language you are trying to use.
考虑以下程序:
int main () {
const int size = 5;
int x[size];
return 0;
}
这将在 C++ 和 C.99 中编译,但不能在 C.89 中编译。在 C.99 中,引入了可变长度数组,因此局部作用域数组可以采用由变量指定的大小。但是,C.99 中文件范围内的数组不能采用可变大小参数,而在 C.89 中,所有数组定义都必须具有非可变大小。
如果您正在使用 C.89,或在 C.99 中定义一个文件作用域数组,您可以使用 enum
来命名您的常量值。然后可以使用 enum
来调整数组定义的大小。然而,这对于 C++ 来说不是必需的,它允许使用由文字初始化的 const
整数类型来调整数组声明的大小。
enum { size = 5 };
int x[size];
int main () { return 0; }
关于c++ - 用声明的常量声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18707271/