Re: Unions Redux
- From: Yevgen Muntyan <muntyan.removethis@xxxxxxxx>
- Date: Thu, 15 Mar 2007 05:55:15 GMT
Jack Klein wrote:
On 14 Mar 2007 15:10:44 -0700, "Old Wolf" <oldwolf@xxxxxxxxxxxxxx>[snip]
wrote in comp.lang.c:
Ok, we've had two long and haphazard threads about unions recently,
and I still don't feel any closer to certainty about what is permitted
and what isn't. The other thread topics were "Real Life Unions"
and "union {unsigned char u[10]; ...} ".
Most of the rambling was caused by the original OP, I think, rather
than the material. I am not criticizing, just observing.
There is no difference in aliasing in a union than there is via
pointer casting.
Sorry if it's something obvious or stupid, but please consider this
(no pointers involved).
Suppose double is eight bytes big, int is four bytes, there are
no padding bits in int.
/* (1) get bits from a double and see what happens */
double a = 3.45; unsigned int b;
memcpy(&b, &a, sizeof b);
printf("%u", b);
/* (2) do same thing using a union */
union U {double a; unsigned int b;} u;
u.a = 3.14;
printf("%u", u.b);
/* (3) initialize union with memcpy and access its member */
double d;
union U {double a; unsigned int b;} u;
d = 3.14;
memcpy(&u, &d, sizeof d);
printf("%u", u.b);
Which of three are valid? I think (1) is; (3) maybe; (2) maybe, if
(3) valid and aliasing rules don't work here. If aliasing rules
do apply to (2), then how is first assignment in (2) different
from memcpy() in (3)?
It's in fact the same question as in the other post by OP, about
aliasing. Perhaps all such magic is allowed and that's it. Perhaps
I'm just stupid that I can't understand these simple things.
Yevgen
.
- Follow-Ups:
- Re: Unions Redux
- From: Jack Klein
- Re: Unions Redux
- References:
- Unions Redux
- From: Old Wolf
- Re: Unions Redux
- From: Jack Klein
- Unions Redux
- Prev by Date: Re: Aliasing rules - int and long
- Next by Date: Re: C89, size_t, and long
- Previous by thread: Re: Unions Redux
- Next by thread: Re: Unions Redux
- Index(es):
Relevant Pages
|