See an example:
#include <iostream>#include<stdio.h>using namespacestd;union A {intA; struct { Shortb; ShortC; };};intMain () {A s; S.A.=0x12345678; printf ("%x%x", s.b, S.C); return 0;}
Output Result:
5678 1234
Why is that so?
Because a is union, the format that is stored in memory is:
High address------------> Low address
12 34 56 78
00010010 00110100 01010110 01111000
S.B occupies a low address of two bytes
S.C occupies a high address of two bytes
So:
s.b = 5678
S.C = 1234
To prove it, and to see more clearly, look at the program below.
#include <iostream>#include<stdio.h>using namespacestd;union A {intA; struct { Shortb; ShortC; };};intMain () {A s; S.A.=0x12345678; printf ("B =%x; c =%x\n", s.b, S.C); printf ("&a =%x; &b =%x; &c =%x\n", &S.A, &s.b, &S.C); return 0;}
Results:
5678 1234&a = 28ff1c; &b = 28ff1c; &c = 28ff1e
Isn't it obvious?
C + + Union memory