The expression must have a constant value error in C ++

Possible duplicate:
Is there a way to initialize an array with mutable variables? (C ++)

I have the following code:

vector<vector<vec2>> vinciP; int myLines = -1; myLines = drawPolyLineFile("vinci.dat", vinciP); if (myLines > -1) { cout << "\n\nSUCCESS"; vec2 vPoints[myLines]; for (int i = 0; i < NumPoints; ++i) { vPoints[i] = vinciP[0][i]; } } 

I get an error in the line vec2 vPoints [myLines]; that expressions must have a constant meaning. I do not understand why I get this error, any help?

Is it because myLines could be negative? Idk.

+8
c ++ arrays vector visual-studio
source share
5 answers
 vec2 vPoints[myLines]; 

Since myLines not a const expression ((this means that it is not known at compile time), therefore the above code declares an array of variable length that is not permitted in C ++. Only C99 has this function. The compiler can have this as an extension ( but this is not a C ++ standard).

The solution to this switching problem: use std::vector<T> as:

 std::vector<vec2> vPoints(myLines); 

Now it should work.

+13
source share

Is it because myLines could be negative?
Not. This is because myLines not a compile-time constant.

Explanation:

 vec2 vPoints[myLines]; 

Creates a variable-length array where the value of myLines will be determined at run time. Variable-length masks are not allowed in C ++. This was a feature introduced in C99, and C ++ Standard does not support it. Some C ++ compilers support it as an extension, but, nevertheless, do not comply with the standard.

For C ++, the size of the array must be known at compile time and, therefore, must be a compile time constant. myLines not a compile-time constant and therefore an error.

You should use std :: vector

+5
source share
 vec2 vPoints[myLines]; 

The size of the array must be a compile time constant. myLines not a compile time constant. Instead, allocate memory with new or even better use std::vector .

+1
source share

C ++ does not have variable length arrays. The size of the array must be determined at compile time. The value of myLines known only at run time, so this will not work.

To have arrays whose size is known only at run time, use std::vector .

 std::vector<vec2> vPoints(myLines); 
+1
source share

You get this error because static arrays need a static (constant) size. Since the number of components in your vPoints is dynamic, consider using a dynamic array instead. Or better yet, stick with vector .

+1
source share

All Articles