问题描述
这可以工作:
this can work:
const int size = 2;
int array[size] = {0};
这里有编译错误:
this has compile error:
int a = 2;
const int size = a;
int array[size] = {0};
为什么?
推荐答案
因为 C++ 委员会的人决定这样做.
Because the guys in the C++ committee decided so.
技术原因是用于初始化size
的第一个表达式是一个常量表达式,它可以在编译期间计算.这意味着编译器还可以知道数组将有多大,并且可以在编译时完成分配(在这种情况下,保留"可能是更合适的术语).
The technical reason is that the first expression that is used to initialize size
is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.
在第二种情况下,表达式不是常量表达式(给定 C++ 定义),并且这种还原是不可能的.
In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.
在第二种情况下,值确实在 size
初始化时固定的事实完全无关紧要.规则基于表达式的种类",第二个表达式使用可变变量,因此编译器认为它是非常量的.
The fact that in the second case the value is indeed fixed by the time size
is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.
允许编译时初始化的第二种形式需要进行流程分析,因为它需要区分
Allowing the second form for compile-time initialization would require a flow analysis because it would need to distinguish between
int a = 2;
const int size = a;
和
int a = foo();
const int size = a;
其中涉及 size
的表达式确实相同.
where the expression involving size
is indeed identical.
这篇关于数组初始化在C++中使用const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!