How is it that "sizeof (char [0])" is compiled with GCC

A colleague of mine inserted a (void) sizeof (char[0])

at the end of a multiline line, a macro as an alternative do {...} while (0)

, apparently. I looked around but I can't find links to it and it surprises me that it even compiles.

Is C really? I would like to get a link to std.

+3


source to share


2 answers


If you compile gcc -pedantic

, you get a warning message:

warning: ISO C forbids zero-size array [-Wpedantic]

      

The latest draft of the C standard, N1570 , section 6.7.6.2 (array declarators) in clause 1 says:

If the expression is a constant expression, it must have a value greater than zero.



This is part of the constraint, and therefore char[0]

a constraint violation, requiring diagnostics from any relevant C compiler.

(It's not 100% clear that this particular sentence applies to a name type char[0]

in the absence of a declared object, but the general idea is that the C standard does not support zero-length arrays.)

gcc supports zero-size arrays as an extension, described here .

+6


source


C11 6.5.3.4/2:

The sizeof operator gives the size (in bytes) of its operand, which can be an expression or a name in parentheses of the type .

/4:

When applied to an operand that is of type array, the result is the total number of bytes in the array.

C11 6.7.7 defines a type name, especially / 2:



In several contexts, the type must be specified. This is done using a type name, which is a syntactic declaration for a function or object of that type, which omits an identifier.

So, char[0]

is a type name because it is syntactically a declaration for an object that omits an identifier. (Semantically, this is invalid as zero-sized arrays are not allowed, but this is still a type name.)


Based on these quotes, I would say sizeof

not specified. 6.5.3.4/2 does not constrain the type name for type names, which would be a legal declaration if an identifier were included. 6.5.3.4/4 does say "array", but no one can agree on what "array" means in C anyway , and I don't think it explicitly implies anything about char[0]

.

Based on these quotes, I would say this is unconvincing.

+2


source







All Articles