# Thread: How does this program work??

1. ## How does this program work??

Can somebody bring some light over this code for I'm not sure how it works... especially with that << operator.

Thanx!!

#include "stdio.h"

union u{
char ch[2];
int num;
}val;

typedef union u u;
int init(u val);

main(void)
{
int x;

x=init(val);

printf("La union contiene %c y %c\n",x,x>>8);

return 0;
}

int init(u val)
{
val.ch[0]='H';
val.ch[1]='I';

return val.num;
}

2. you have the source, yet you dont understand it. I'm assuming that its not your's. If you want to learn things, you need to learn stuff as you go. You dont get the source for Adobe PS and say "Hey, how does this code work?".

3. ## Useless

That was useless

4. [very meaningfull post]Wha?[/very meaningfull post]

5. 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.