I know VLAs have their own properties, but is there any practical difference (either performance or otherwise) between an array and a VLA with a known size?
For example:
inline int createVLA(int size)
{
int VLA[size];//compiler can deduce that size == 7
return sizeof(VLA);
}
int main()
{
int i = 5;
return createVLA(i + 2);
}
I know this program could technically be optimized away almost entirely, but imagine if the VLA was actually used for something.
There are at least three differences.
One, a variable-length array cannot be declared with thread_local
, static
, or extern
:
static int A[4]; // Okay.
static int B[size]; // Error.
(Technically, the C standard just requires a diagnostic for the latter, after which an implementation can do anything, including supporting it. Somehow.)
Two, the size of a variable-length array is not a constant expression:
int A[4], B[size];
static int x = sizeof A; // Okay.
static int y = sizeof B; // Error.
(Again, technically an implementation could somehow support the size of a variable-length array as a constant expression even though the C standard does not require it.)
Three: The lifetime of a fixed-length array begins when execution enters its block, while the lifetime of a variable-length array begins when execution reaches its declaration:
switch (2)
{
int A[4];
int B[size];
…
case 2:
A[0] = 3; // Okay.
B[0] = 3; // Error, B does not exist yet.
…
}