Tomaž Stoiljkovič Tomaž Stoiljkovič - 11 months ago 91
C++ Question

Same code compiling in g++, but not in VS

I am trying to run my code in Visual Studio 2015, and I get next error

expression must have a constant value
double x1[dim];
in next code snipped.

double fitness(const double x[], const int &dim) {
double sum = 0.0;
double x1[dim];
return sum;

The same code runs without an error on
g++ 4.8
. So how can I do the same thing under Visual Studio 2015.

Is my problem with compiler or code implementation?

Answer Source

double x1[dim]; is a VLA (variable length array). It is not standard C++.

The reason why it works on gcc is that gcc has an extension which allows VLAs. VS2015 doesn't, so that's why it doesn't compile (it has its own set extensions though, just not that one).

The best alternative is a std::vector:

std::vector<double> x1(dim); //array of size dim

If you can't use that, you can still use a manual dynamic array (although that is not recommended):

double* x1 = new double[dim];
delete[] x1; //Don't forget to delete it when you are done
//Alternatively, create a class which wraps the dynamic array, so you can use RAII