Unions Redux



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]; ...} ".

Here's a concrete example:

#include <stdio.h>

int main(void)
{
union { int s; unsigned int us; } u;

u.us = 50;
printf("%d\n", u.s);
return 0;
}

Is this program well-defined (printing 50), implementation-defined, or
UB ?

Note that the aliasing rules in C99 6.5 are not violated here -- it is
not forbidden under that section to access an object of some type T
with an lvalue expression whose type is the signed or unsigned
version of T.

In other words, is there anything other than the aliasing rules that
restrict 'free' use of unions?

.



Relevant Pages

  • Re: Unions Redux
    ... The other thread topics were "Real Life Unions" ... union {int s; unsigned int us;} u; ... Note that the aliasing rules in C99 6.5 are not violated here -- it is ... C99: well-defined. ...
    (comp.lang.c)
  • Re: Unions Redux
    ... The other thread topics were "Real Life Unions" ... union {int s; unsigned int us;} u; ... Note that the aliasing rules in C99 6.5 are not violated here -- it is ... It is undefined because the member of the union accessed is not the ...
    (comp.lang.c)
  • Re: properly using unions.
    ... I want to save up some space by using unions. ... typedef struct svarrec { ... short int dtype; /* These 4 bytes also accessed as int using asint ... char spare; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)
  • Re: Consideration on pointer declarations
    ... expecially complex ones with embedded typedef'd unions. ... typedef struct ... int serial_number; ...
    (comp.lang.c)