Is `void foo(int a[static 0]);` valid?

126 Views Asked by At

Is the following function strictly compliant to C99?

void foo(int a[static 0]) {
  (void)a;
}

Both GCC and Clang emits warning about using zero-sized array but I don't think this warning is justified. AFAIK, the 6.7.6.3p7 tells the static keyword indicates that the pointer a should point to at least zero elements, a requirement that is trivially satisfied by any pointer with determinate value.

Moreover, can such a function be called in the following cases:

int i;
foo(NULL);
foo(&i);
foo(&i + 1);
2

There are 2 best solutions below

6
Eric Postpischil On BEST ANSWER

AFAIK, the 6.7.6.3p7 tells the static keyword indicates that the pointer a should point to at least zero elements,…

6.7.6.3 7 is not the only rule that applies.

As you know, a parameter declared as an array is automatically adjusted to be a pointer. But before it is adjusted, it is a parameter declared as an array. One of the rules for array declarators is a constraint in 6.7.6.2 1:

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or * . If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero…

Violating 6.7.6.2 1 is a constraint violation even if 6.7.6.3 7 is satisfied.

… point to at least zero elements, a requirement that is trivially satisfied by any pointer with determinate value.

No, it is not. First, a null pointer does not point to at least zero elements because it does not point to anything.

Second, the pointer is not merely required to point to at least zero elements but specifically to the first element of an array with at least zero elements. Any array that has at least zero elements has at least one element, because 6.2.5 20 defines an array type as “contiguously allocated nonempty set of objects with a particular member object type”. So the mere fact it is an array means it has at least one element.

Therefore, even if declared int a[static 0], a must point to at least one int.

0
Lundin On

It is not compliant since arrays cannot have size 0. And therefore not "at least 0" either.

C17 6.7.6.2 emphasis mine:

Constraints

In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero.

(In C99 the same text is found below 6.7.5.2)