C++ requires constant expressions — expressions that evaluate to a constant — for declarations of:
-
Array bounds
-
Selectors in case statements
-
Bit-field length specification
-
Enumeration initializers
The only operands that are legal in constant expressions are:
-
Literals
-
Enumeration constants
-
Values declared as const that are initialized with constant expressions
-
sizeof expressions
Nonintegral constants must be converted (either explicitly or implicitly) to integral types to be legal in a constant expression. Therefore, the following code is legal:
const double Size = 11.0;
char chArray[(int)Size];
From: http://msdn.microsoft.com/en-us/library/3ffb821x.aspx
So we don't need to have constant expression when initialize a const variable:
int i = -1;
const int ic = i; //legal.
本文详细介绍了C++中常量表达式的使用场景及合法元素,包括数组边界、case语句选择器、位字段长度等,并举例说明了非整型常量如何转换为整型以符合语法要求。
2836

被折叠的 条评论
为什么被折叠?



