问题
This is my code:
int main()
{
const int LEN = 5;
int x[LEN];
}
VS10 says:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'x' : unknown size
I even tried the the code in this page and it gives the same problem (I commented the code which gives the error, and uncommented the correct one): http://msdn.microsoft.com/en-us/library/eff825eh%28VS.71%29.aspx
If I was trying a crappy compiler, I would think it's a bug in the compiler, but it's VS2010!
回答1:
You might have compiled your code using .c extension. MS Visual C doesn't support C99. In C89 the size of an array must be a constant expression. const
qualified variables are not constants in C. They cannot be used at places where a real constant is required.
Also read this excellent post by AndreyT.
Try saving the file with .cpp extension.
回答2:
As per http://msdn.microsoft.com/en-us/library/3ffb821x.aspx, "Values declared as const that are initialized with constant expressions" are legal in array bounds, so this is valid C++ code.
Thus, that's either a compiler bug or something bizarre coming off a #define somewhere. As sje397's comment suggests, try some name other than LEN
for the length? Also, is that actually your entire code, or are headers being #included as well?
Edit to add: Also, the fact that this is valid C++ code of course doesn't matter if you're compiling this as C, as others have noted.
回答3:
You could also use
int main()
{
enum { LEN = 5 };
int x[LEN];
}
回答4:
because in this case, I can do :
int main()
{
const int LEN = 5;
int* LENptr = (int*)(&LEN);
*LENptr = 10;
int x[LEN];
}
which const is only means read-only in this code, not compile-time constant
来源:https://stackoverflow.com/questions/4457978/how-come-the-compiler-thinks-this-variable-isnt-constant