Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can C++ functions create arrays of variable lengths?

According to this answer, which states:

The compiler knows the size of the int type and therefore can generate the right assembler instruction that will reserve enough space on the stack in order to let foo live there.

a compiler needs to know the size a function will occupy on the stack in order to implement it.

Then, why does this code compile?

int f(int n)
{
    int x[n];
}

int main()
{
    f(3);
    f(5);
    //etc
}

x is an array of integers, but its size isn't constant, it can change any time the function is called.

What am I missing here?

like image 957
corazza Avatar asked Apr 08 '13 19:04

corazza


2 Answers

This is not legal code in Standard C++. It compiles thanks to an extension specific to your compiler which supports variable-length arrays, which is a C99 feature.

But again, this is not portable C++. If you need dynamic sizing, you could rewrite your function this way:

#include <vector>

int f(int n)
{
    std::vector<int> v(n);
}

Otherwise, make it a template and write it this way:

#include <array>

template<std::size_t N>
int f()
{
    std::array<int, N> a;
}
like image 96
Andy Prowl Avatar answered Sep 25 '22 05:09

Andy Prowl


It compiles because you're using a non-standard extension. In the strict sense, it's not valid C++, but some compilers do support this.

In your case (3 and 5 are known), you can use templates instead, which would be valid, or directly a std::vector.

template<int n>
int f()
{
    int x[n];
}

//...
f<3>();
like image 23
Luchian Grigore Avatar answered Sep 21 '22 05:09

Luchian Grigore