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?
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;
}
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With