[comp.lang.c] Save to assign union member to each other ?

michi@ptcburp.ptcbu.oz.au (Michael Henning) (02/07/91)

Something I could not figure out from the various references...

Given

union {
	int	i;
	double	d;
} u;

is it legal to assign one member of the union to another?  Examples:

	u.i = !u.d;
	u.d = (double)u.i;
	u.d = (double)(u.i * 3.14);

The various standard references (K&R, Harbison & Steele) are not clear
about this. Obviously, the address of the lvalue on the left may be the
same as the address of one or more operands in the expression on the right,
as in

	x = -x * x;

But what about the case where the union contains objects of different types
and sizes, as above? It looks legal to me. Has anyone ever encountered a
compiler that generates incorrect code for such a case?

							Michi.

-- 
      -m------- Michael Henning			+61 75 950255
    ---mmm----- Pyramid Technology		+61 75 522475 FAX
  -----mmmmm--- Research Park, Bond University	michi@ptcburp.ptcbu.oz.au
-------mmmmmmm- Gold Coast, Q 4229, AUSTRALIA	uunet!munnari!ptcburp.oz!michi

thorinn@diku.dk (Lars Henrik Mathiesen) (02/09/91)

michi@ptcburp.ptcbu.oz.au (Michael Henning) writes:
>Given

>union {
>	int	i;
>	double	d;
>} u;

>is it legal to assign one member of the union to another?  Examples:

Under Semantics of 3.3.16.1 (Simple assignment), the C Standard says:

"If the value being stored in an object is accessed from another object
 that overlaps in any way the storage of the first object, then the
 overlap shall be exact and the two objects shall have qualified or
 unqualified version of a compatible type; otherwise the behavior is
 undefined."

The answer to your question is no.

--
Lars Mathiesen, DIKU, U of Copenhagen, Denmark      [uunet!]mcsun!diku!thorinn
Institute of Datalogy -- we're scientists, not engineers.      thorinn@diku.dk