Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expression must have a constant value error in c++ [duplicate]

Possible Duplicate:
Is there a way to initialize an array with non-constant 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'm getting an error on the line 'vec2 vPoints[myLines];' that says expressions must have a constant value. I don't understand why I'm getting this error, any help?

Is it because myLines could be negative? idk.

like image 363
y3di Avatar asked Sep 20 '11 15:09

y3di


1 Answers

vec2 vPoints[myLines];

Since myLines is not a const expression ((which means, it is not known at compile-time), so the above code declares a variable length array which is not allowed in C++. Only C99 has this feature. Your compiler might have this as an extension (but that is not Standard C++).

The solution to such commom problem is : use std::vector<T> as:

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

It should work now.

like image 124
Nawaz Avatar answered Oct 17 '22 08:10

Nawaz