[comp.std.c] Question about unions

walter@hpcllz2.HP.COM (Walter Murray) (05/26/88)

Section 3.5.2.1 of the January draft, after permitting holes
in structure objects, goes on to say,

  "There may also be unnamed padding at the end of a structure,
  as necessary to achieve the appropriate alignment were the
  structure to be a member of an array."

Is there any reason a similar statement is not made about unions?
Section 3.3.3.4 (the sizeof operator) certainly implies that a
union may have padding.

Walter Murray

karl@haddock.ISC.COM (Karl Heuer) (05/28/88)

In article <16490002@hpcllz2.HP.COM> walter@hpcllz2.HP.COM (Walter Murray) writes:
>[The dpANS mentions that there may be padding at the end of a structure.]
>Is there any reason a similar statement is not made about unions?
>Section 3.3.3.4 (the sizeof operator) certainly implies that a
>union may have padding.

I don't agree that 3.3.3.4 implies it, but I think that it does have to be
allowed.  The existence of pointers to incomplete types requires that a
word-addressible machine use a consistent format for pointer-to-union
(likewise for pointer-to-struct; this has been expressed as "all struct
pointers smell the same"), and I believe the usual choice for this is word
pointers -- which means that union{char} contains trailing padding.  Looks
like 3.5.2.1 should be reworded to mention unions.

Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint

walter@hpcllz2.UUCP (06/03/88)

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