Zero Length Arrays Allowed in C Standard?

Spencer Garrett srg at quick.COM
Thu Dec 7 19:31:47 AEST 1989


In article <11760 at smoke.BRL.MIL>, gwyn at smoke.BRL.MIL (Doug Gwyn) writes:
> In article <2678 at cbnewsj.ATT.COM> asd at cbnewsj.ATT.COM (adam.denton,mt,) writes:
> >What fathomable purpose could a programmer possibly want by
> >declaring a zero-length array?  To store nothing?
> 
> What fathomable purpose could a programmer possibly want by
> coding a loop that gets executed zero times?  To do nothing?

Excellent point.  Bravo!  I'm going to save your article for
the next time this comes up!

> Possible uses for zero-sized objects (notably arrays) have
> already been posted.  Let me add that there are no logical
> problems with the concept; all properties of such objects
> would be well defined.
> 	sizeof zero would be 0
> 	&zero points at the object
> 	++ptr_to_zero would still point to zero
> 	*ptr_to_zero needn't do anything to "access" the contents
> 	&zero_length_array[0] points one past the last valid element
> etc.

Just some minor nits so as not to confuse those who are still having
trouble with this concept.

	++ptr_to_zero   *will* increment the pointer.  The *array*
has size 0.  Its *elements* do not.  There just aren't any *of*
them.  Thus sizeof(zero) == 0,  sizeof(zero[0]) > 0, and
(sizeof(zero)/sizeof(zero[0])) gives the number of elements in
the array (as always) which in this case happens to be 0.

	*ptr_to_zero   will access storage wherever the pointer
points.  If that's beyond the end of the malloc'd storage it may
bomb like any other array reference.  If the array was statically
allocated, then this is always an illegal reference.

	&zero_length_array[0]   does indeed point one past the
last valid element.  It also points to the first element of the
array, but that element *isn't a valid element* unless the
array has been expanded via malloc (or friends).

> As I recall, zero was invented by Arabic mathematicians
> thousands of years ago.  It's a pity it still frightens
> or confuses people.

Yup.  At least we're not burning heretics so often anymore.

Actually, I must confess that structures with no members
of nonzero size do cause some problems, but arrays of
length zero make perfect sense, and that's the usage that
started this discussion.



More information about the Comp.lang.c mailing list