0

The code compiles and runs, but is it legal? AFAIK, size of static array must be known at compile time.

#include <iostream>
void foo(const unsigned size){
    double arr[size];
    for(auto& i:arr){
        i=2;
        std::cout << i;
    }
}

int main(){
    unsigned size;
    std::cin >> size;
    foo(size);
}
BlueTrin
  • 9,610
  • 12
  • 49
  • 78
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52

3 Answers3

3

Strictly speaking, this is not legal. Variable length arrays (VLA) are not supported by standard C++. VLA are supported by most compilers an an extension but using those may give you non portable behavior.

Also, there is no static array in your source code. To do so you would need to use the static keyword on the declaration.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

As user657267 mentioned, Runtime-size arrays have been discussed for C++14 in N3639 and another similar feature, std::dynarray has been discussed, however they have been rejected for C++14.

Currently, this is not considered as part of the standard although some compilers implemented this as non-portable extensions, gcc for example is one of these compilers (possibly because this is legal in C99).

Most of the time, you can just use a vector to the same effect.

BlueTrin
  • 9,610
  • 12
  • 49
  • 78
0

In your example there is no array with the static storage duration. There is a local array within a function with automatic storage duration. The size of the array shall be a constant expression.

If the code you showed is compiled then it means it is a feature of the compiler that supports Variable Length Arrays in C++ the same way as in C.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335