Type punning in C

Karl Heuer karl at haddock.ima.isc.com
Sat Oct 21 05:03:32 AEST 1989


In article <6310 at arcturus> evil at arcturus.UUCP (Wade Guthrie) writes:
>I thought that the standard said (as opposed to what I remember reading
>in K&R I) that members of unions do NOT have to have zero offset?

The pANS guarantees that a pointer to a union, suitably cast, points to each
of its members, and vice versa.

It also says that the behavior is undefined if you use a union for punning.
(What else could it say?  You can't close your eyes and pretend that the
behavior is predictable!)  Since you already know your program isn't portable,
you needn't worry about this.

It may be that the undefined-behavior clause would permit an implementation
where punning doesn't work and differently-typed union members don't overlap,
provided that appropriate code is generated when casting to/from a union type.
This may be the source of the rumor you heard.

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



More information about the Comp.lang.c mailing list