0

I am relatively new to C++ and switched operating devices from windows to mac. I did encounter a lot of problems while installing the same and is also the reason why I am asking this question. Previously the following code (Please note that the same libraries are initialized and the same code is written outside the main block.)

on Windows:

int main(){
    int n  = 5;
    int array[n] = {7, 4, 2, 8, 1} ;
    insertionSort(array, n);
}

works perfectly well for me while on mac (apple silicon) i get the following error:

stdc.cpp:6:13: error: variable-sized object may not be initialized
    int arr[n] = {7, 4, 2, 8, 1};

Is this an OS thing which restricts me from initializing a variable length to an array and assigning a value or did I install it incorrectly? Please note that I used VS Code on both.

rioV8
  • 24,506
  • 3
  • 32
  • 49
  • 3
    C++ standard does **not** support VLAs (variable length arrays). – wohlstad Oct 11 '22 at 14:08
  • 1
    VLA are illegal in C++. You didn't configure your first compiler correctly to strictly follow C++ standards. – Revolver_Ocelot Oct 11 '22 at 14:08
  • `int n = 5; int array[n] = {7, 4, 2, 8, 1} ;` has never been legal to do. add `-pedantic-errors` to your compiler command to stop this from being accepted. – NathanOliver Oct 11 '22 at 14:09
  • clang is correct. Declare `const int n = 5;` Or better yet, `constexpr int n = 5;`. Or better yet, use `std::array`. – sweenish Oct 11 '22 at 14:09
  • 2
    I really wish g++ would turn off this "feature". – NathanOliver Oct 11 '22 at 14:09
  • @wohlstad I was able to run the code properly as well though. If cpp doesn't support VLA in the first place shouldnt I have encountered an error there too? – maxdoesmax Oct 11 '22 at 14:10
  • Some compilers support it, to some extent. But proper C++ code should avoid it. See: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard. – wohlstad Oct 11 '22 at 14:11
  • @maxdoesmax Exactly [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) – Jason Oct 11 '22 at 14:12
  • This is where you prefer to use `std::vector`, as `std::vector` can resize at run-time. – Thomas Matthews Oct 11 '22 at 17:46

0 Answers0