There is no right behavior. Setting a union through one element and extracting a value from another member causes undefined behavior. You can do useful things with this technique, but it depends on the hardware and the compiler. You will need to consider processor and memory matching requirements.
Back when I was doing almost all of my C programs, there were two (portable) methods using unions, which I relied quite heavily on.
Marked Union . This is great when you need a dynamically typed variable. You create a structure with two fields: a type discriminator and a union of all possible types.
struct variant { enum { INT, CHAR, FLOAT } type; union value { int i; char c; float f; }; };
You just had to be very careful to set the type value correctly whenever you change the union value and retrieve only the value specified by the type.
General pointers . Since you can be sure that all pointers are the same size and presentation, you can create a union of types of pointers and know that you can set and retrieve values interchangeably, regardless of type:
typedef union { void *v; int* i; char* c; float* f; } ptr;
This is especially useful for (de) serializing binary data:
// serialize ptr *p; pv = ...; // set output buffer *p.c++ = 'a'; *p.i++ = 12345; *p.f++ = 3.14159; // deserialize ptr *p; pv = ...; // set input buffer char c = *p.c++; int i = *p.i++; float f = *p.f++;
FYI:. You can make your example simpler. Structures are not needed. You will get the same behavior:
int main() { union { int a; char b; } v1; v1.a = 5; v1.b = 'a'; }
source share