Re: Unions Redux



Jack Klein wrote:
On 14 Mar 2007 15:10:44 -0700, "Old Wolf" <oldwolf@xxxxxxxxxxxxxx>
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.
[snip]
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
.



Relevant Pages

  • Re: Unions Redux
    ... pointer casting. ... union U {double a; unsigned int b;} u; ... valid and aliasing rules don't work here. ...
    (comp.lang.c)
  • [PATCH] netfilter endian regressions
    ... struct xt_connlimit_info { ... unsigned int limit, inverse; ... union nf_conntrack_man_proto ... static inline bool already_closed ...
    (Linux-Kernel)
  • Re: Undefined behavior - 2 queries
    ... suitable-selected unsigned int to access all the bits within a float. ... optimization affect the access of float representation through a union ... Reading email is like searching for food in the garbage, ...
    (comp.lang.c)
  • [PATCH 13/19] dmaengine: add support for dma xor zero sum operations
    ... unsigned int src_off, size_t len, unsigned long flags); ... union dmaengine_addr dest, unsigned int dest_off, ... DMA channel to offload zero sum to ...
    (Linux-Kernel)
  • Re: Unions Redux
    ... of course there are pointers involved. ... union U {double a; unsigned int b;} u; ... valid and aliasing rules don't work here. ...
    (comp.lang.c)