1

In the comments to this former question, there was a discussion if the C standard allows variable length arrays (VLAs) of length 0 or not. As it turns out, the C99 standard states:

In 6.7.5.2 Array declarators, Constraints:

"If the expression [for the array size] is a constant expression, it shall have a value greater than zero."

So since the standard explicitly mentions "constant expressions", it is clear that this constraint shall not hold for non-constant expressions, means zero length VLAs are allowed. This is indeed a useful behaviour, so for example GCC introduced it long before C99 as an extension and supports this AFAIK currently.

On the other hand, the C11 standard (draft) in 6.7.6.2 (Array declarators, Constraint 5) says:

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.

So this explicitly forbids VLAs with zero length arrays. For example, according to this change, a function like

void MySpecialProcessing(int n, int *data)
{
    int sortBuffer[n];
    // ... do something with data, using sortBuffer ...
}

maybe C99 compliant without any special treatment for n==0, but in C11, it must be

void MySpecialProcessing(int n, int *data)
{
    if(n==0)
        return;

    int sortBuffer[n];
    // ... 
}

Normally I would expect newer versions of the standard to introduce features which makes the life easier for the programmer, but in this case IMHO this seems a step back.

So any idea why this incompatible, breaking change was introduced? Is this intentional, or just a bug in the C11 standard?

1

There has been no breaking change in this regard between C99 and C11.

The C99 standard states in section 6.7.5.2/5 (under Semantics):

If the size is an expression that is not an integer constant expression: [...]; otherwise, each time it is evaluated it shall have a value greater than zero. [...]

As this is not a constraint, violating the 'shall' results in undefined behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.