Question about unions

walter at hpcllz2.UUCP walter at hpcllz2.UUCP
Sat Jun 4 03:05:22 AEST 1988


My thanks to those who have responded by mail.  I've had
some difficulty in replying, so will post here.

Some have expressed the view that a union should not need
padding, that the size of a union should be the size of
its longest member.  Here is a counterexample, I think.

Consider an implementation where sizeof(int)==4 and an int
is required to be aligned on a 4-byte boundary.  Take
the following declaration.

union {
   int i;
   char ca[5];
   } ua[2];

I assert the following:

   sizeof (ua[0].i) == 4
   sizeof (ua[0].ca)== 5
   sizeof (ua[0])   == 8

The union must have three bytes of trailing padding.

Am I wrong?

Walter Murray



More information about the Comp.std.c mailing list