On 6/6/05, Segher Boessenkool <[EMAIL PROTECTED]> wrote:
> > Better use a union for the (final) conversion, i.e
> >
> > int conv(unsigned char *c)
> > {
> >     unsigned int i;
> >     union {
> >         unsigned int u;
> >         int i;
> >     } u;
> >
> >     u.u = 0;
> >     for (i = 0; i < sizeof u; i++)
> >       u.u = (u.u << 8) + c[i];
> >
> >     return u.i;
> > }
> 
> This is not portable, though; accessing a union member other than
> the member last stored into is unspecified behaviour (see J.1 and
> 6.2.6.1).
> 
> This is allowed (and defined behaviour) as a GCC extension, though.

I guess this invokes well-defined behavior on any sane implementation,
as otherwise treatment of a pointer to such union would be different to
that of a pointer to a member of such union.  Aka you would get undefined
behavior once you read bytes from a file and access them as different
types.  Also this technique is cited to circumvent type aliasing issues
for f.i. doing bit-twiddling of floats on its integer representation.

But I guess following the standard, you are right :(

Richard.

Reply via email to