c++ccompiler-errors

How come the compiler thinks this variable isn't constant?


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!


Solution

  • 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.