Just curious, what actually happens if I define a zero-length array int array[0];
in code? GCC doesn\'t complain at all.
Sample Program
Zero-size array declarations within structs would be useful if they were allowed, and if the semantics were such that (1) they would force alignment but otherwise not allocate any space, and (2) indexing the array would be considered defined behavior in the case where the resulting pointer would be within the same block of memory as the struct. Such behavior was never permitted by any C standard, but some older compilers allowed it before it became standard for compilers to allow incomplete array declarations with empty brackets.
The struct hack, as commonly implemented using an array of size 1, is dodgy and I don't think there's any requirement that compilers refrain from breaking it. For example, I would expect that if a compiler sees int a[1]
, it would be within its rights to regard a[i]
as a[0]
. If someone tries to work around the alignment issues of the struct hack via something like
typedef struct { uint32_t size; uint8_t data[4]; // Use four, to avoid having padding throw off the size of the struct }
a compiler might get clever and assume the array size really is four:
; As written foo = myStruct->data[i]; ; As interpreted (assuming little-endian hardware) foo = ((*(uint32_t*)myStruct->data) >> (i << 3)) & 0xFF;
Such an optimization might be reasonable, especially if myStruct->data
could be loaded into a register in the same operation as myStruct->size
. I know nothing in the standard that would forbid such optimization, though of course it would break any code which might expect to access stuff beyond the fourth element.