2

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?

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
iammilind
  • 68,093
  • 33
  • 169
  • 336

3 Answers3

4

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

M.M
  • 138,810
  • 21
  • 208
  • 365
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
4

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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.

Grizzly
  • 19,595
  • 4
  • 60
  • 78