1

I am trying to run my code in Visual Studio 2015, and I get next errorexpression must have a constant valueon 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?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
TomazStoiljkovic
  • 808
  • 8
  • 21
  • use std::vector or std::valarray – user3528438 Sep 25 '16 at 11:15
  • I am trying to avoid containers like std::vector or std::array. – TomazStoiljkovic Sep 25 '16 at 11:18
  • 1
    Then you can use dynamic array (`new` and `delete`), although I would prefer std::vector over it unless there is a very compiling reason. BTW the reason your code does't work is, variable length array, aka, VLA, is a c99 feature and is supported by GCC as a extension by default (afaik GCC's default C++ dialect option is -std=gnu++98 with all gcc extensions enabled ). MSVC traditionally has a bad support for C99 so this language feature is likely not available in MSVC. – user3528438 Sep 25 '16 at 11:26
  • `g++ -Wall -std=c++14 -pedantic test.cpp` wouldn't compile the above code since [VLA](https://en.wikipedia.org/wiki/Variable-length_array)s isn't part the C++ standard; C99 allows it but you should use `gcc` for that. – legends2k Sep 25 '16 at 11:44

2 Answers2

3

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
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
1

In the past, when I wanted to use VLA on MSVC, a workaround was to use alloca() whenever I wanted or needed VLA feature on a compiler that does not support VLA.

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177