Search code examples
arraysclanguage-lawyerincomplete-typealignof

C2x: if _Alignof(array type) yields the alignment of the element type, then will it be useful to permit _Alignof(incomplete array type)?


This code is invalid:

int x = _Alignof(int[]);

Note: GCC produces:

error: invalid application of '__alignof__' to incomplete type 'int[]'

while Clang produces:

<nothing>

Per Semantics (emphasis added):

When applied to an array type, the result is the alignment requirement of the element type.

However, in order to yield the alignment requirement of the element type, the size is not needed.

Hence, will it be useful to make the code above valid by changing the constraint

from:

The _Alignof operator shall not be applied to a function type or an incomplete type.

to (emphasis added):

The _Alignof operator shall not be applied to a function type or an incomplete non-array type.


Solution

  • C2x: if _Alignof(array type) yields the alignment of the element type, then will it be useful to permit _Alignof(incomplete array type)?

    As you observe, the language spec explicitly forbids applying the _Alignof operator to an expression of incomplete type or to the parenthesized name of such a type. This is a language constraint, so it is a conformance requirement that implementations diagnose violations, and in this sense, Clang's behavior is non-conforming.

    On the other hand, you're right that there is an opportunity for fully consistent _Alignof behavior when the type in question is an array type with complete element type but unspecified number of elements. The number of elements in an array is not a factor in its alignment requirement, so this operation could be resolved according to ordinary _Alignof semantics, provided only that the spec allowed it.

    Would it be useful? I'm sure that depends on what range of possible uses one considers. I don't find _Alignof very useful in general, though it does have its moments. And since you can get the alignment of an array type directly from its element type, you don't need _Alignof for array types -- complete or not -- except in places where you don't know what type will be operated upon. That doesn't cut out all possible uses, but the window it leaves is small enough that I don't think it unreasonable for the spec to express the simpler constraint it does instead of the more complicated one that would be required to allow _Alignof on this one special class of incomplete types.