0

I'm very new to C++, but I've been digging around and the general answer is no, c++11 does not support variable sized arrays, since array sizes need to be constant expressions.

However, I've tried this code on XCode 11 (C++11):

#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {

    unsigned long arrayS;
    cin >> arrayS;

    bool a[arrayS];

    return 0;
}

and it totally works. When I set a breakpoint at

bool a[arrayS];

I can see that the array a has arrayS elements. I have verified this with

*(&a + 1) - a

and it shows that the number of elements in a is arrayS.

Does c++11 support variable sized arrays? Or, is it only working for me because of the compiler I'm using?

I'm asking this question because I'm unsure of what compiler my friend is using and want to send the code to him to run.

Any help is much appreciated.

Ryan Zhang
  • 1,856
  • 9
  • 19
  • *Does c++11 support variable sized arrays?* -- No. You will quickly realize this if you use Visual Studio, as that code will fail to compile. Dynamic arrays in C++ are spelled `std::vector`. – PaulMcKenzie May 09 '20 at 05:23
  • Your compiler will have options to turn off non-standard extensions. You should pick those options to be confident that the code your send to our friend is standard. Sorry but I don't know what those options are on XCode, but they definitely exist. Consult your documentation. – john May 09 '20 at 05:42

2 Answers2

1

That is non standard C++. Some compilers accept it, but if you want to be portable you should stick with standard C++.

darcamo
  • 3,294
  • 1
  • 16
  • 27
0

In c++, array size should be supplied at compile time. For variable sized arrays use std::vector

Imanpal Singh
  • 1,105
  • 1
  • 12
  • 22
Roy2511
  • 938
  • 1
  • 5
  • 22