Code:
union u{
char ch[2];
int num;
}val;
The size of a union is the sizeof the largest variable in it, which is inturn machine and OS dependant. Assuming sizeof(char) = 1 and sizeof(int) = 2 on your machine, the sizeof(union u) = 2. Also note that, all the variables in a structure have the same address, hence &val.ch[0] = &val.num
With:
Code:
val.ch[0]='H';
val.ch[1]='I';
You are only initializing the first 2 bytes allocated to it. And now, the lower 8bits of the variable 'num' has the value 'H' and the higher order 8bits has the value 'I'. So, the data at &val (or &val.ch[0] or &val.num) would look like:
&val.ch[0] &val.ch[1]
---------- ----------
01001001 01001000
'I' 'H'
<< is the Left Shift Operator and >> is the Right Shift Operator, which shift's each bit left/right the specified number of times.
Thus:
(0100100101001000 >> 8) = 0000000001001001 = 01001001 = 'I'
Code:
printf("La union contiene %c y %c\n",x,x>>8);
The first argument will print 'H' (since it's a char you are printing, only the first 8bits will be considered, which are: 01001000 = 'H') and then when you x>>8, 'I' will be produced.
All the operations and results are assumed to be on the little-endian machines.