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?
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).