3

In windows MSVC, I was trying to compile the below code.

void foo(std::vector<double> &bar){
    const long int length = bar.size();
    double a[length]; //error C3863: array type 'double [length]' is not assignable
    for(int i=0; i < length; i++){
        a[i]=0.0;
    }
    //do some other things
}

the code works fine in xcode.

When I switch to MSVC, compile the code with command line:

cl /EHsc main.cpp /std:c++17

Then I have the "error C3863: array type 'double [length]' is not assignable".

Why is it different? How to get rid of the error?

Xuhang
  • 445
  • 5
  • 20
  • 6
    `double a[length];` is a [VLA](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) (not included in standard C++). Make `a` a `std::vector` instead: `std::vector a(bar.size());` would do what you are trying to do now, but using standard C++. It has the added benefit that you don't need to set all values to `0.0` afterwards too. – Ted Lyngmo Nov 10 '20 at 21:37
  • 1
    `double a[length];` is not legal C++, XCode is misleading you. Array bounds must be compile time constants, `length` is a variable. Use a `std::vector` instead. – john Nov 10 '20 at 21:39
  • 2
    Some C++ compilers implement VLA as an extension. MSVC is not one of them. – Fred Larson Nov 10 '20 at 21:40
  • 3
    I suggest that you add `-Wall -Wextra -pedantic -pedantic-errors` when compiling from xcode to not get surprises like this when trying to compile your programs with other compilers. – Ted Lyngmo Nov 10 '20 at 21:49

1 Answers1

8

double a[length]; is not portable C++ as variable length arrays are not implemented by the language.

std::vector<double> a(bar.size());

is the replacement. Note that the elements will be initialised to zero for you, so you can remove the initialisation loop.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483