Is the sizeof operator evaluated differently for VLAs by gcc?
-
13-04-2021 - |
Question
g++
allows Variable Length Arrays (VLA) as an extension. The results of sizeof
operator on VLAs are interesting:
int main ()
{
char size = 20, a[10], b[size];
cout<<"sizeof(a) = "<<sizeof(a)<<endl; // sizeof(a) = 10, (can be used as template param)
cout<<"sizeof(b) = "<<sizeof(b)<<endl; // sizeof(b) = 20 !! (can't used be as template param)
}
In case of sizeof(b)
, is g++ not following the standard where sizeof
is evaluated only at compile time? Is sizeof
overloaded?
Solution
VLAs are an exception to the rule that the operand of sizeof
is not evaluated, as specified in C99, 6.5.3.4/2:
If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
This behaviour is a g++ extension; in Standard C++ (up to and including C++14) the operand of sizeof
is never evaluated (and VLAs are not permitted).
OTHER TIPS
VLAs were introduced in C99. In C99, sizeof(vla)
is not a compile-time constant, but takes into account the run-time size of the array.
gcc/g++
allow VLAs in non-C99 code, as an extension. When doing so, the compilers follow the C99 semantics. This is what you're observing.
Variable Length Arrays are a part of C99, which is not in C++. Gcc allows them as an extension in C++ using the behaviour from C99, which does indeed say that sizeof
returns the actual size of the array (and is therefore evaluated at runtime). The wikipedia article about sizeof gives a nice summary of its behaviour.