The 2011 standard explicitly states...
6.7.6.2 Array declarators
- If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by
*
; otherwise, each time it is evaluated it shall have a value greater than zero. The size of each instance of a variable length array type does not change during its lifetime. Where a size expression is part of the operand of asizeof
operator and changing the value of the size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated.
It's contrived, but the following code seems reasonable.
size_t vla(const size_t x) {
size_t a[x];
size_t y = 0;
for (size_t i = 0; i < x; i++)
a[x] = i;
for (size_t i = 0; i < x; i++)
y += a[i % 2];
return y;
}
Clang seems to generate reasonable x64 assembly for it (without optimizations). Obviously indexing a zero length VLA doesn't make sense, but accessing beyond bounds invokes undefined behavior.
Why are zero length arrays undefined?