I was reading about union in C from K&R, as far as I understood, a single variable in union can hold any one of the several types and if something is stored as one type and extracted as another the result is purely implementation defined.
Now please check this code snippet:
#include<stdio.h>
int main(void){
union a{
int i;
char ch[2];
};
union a u;
u.ch[0] = 3;
u.ch[1] = 2;
printf("%d %d %d\n",u.ch[0],u.ch[1],u.i);
return 0;
}
Output:
3 2 515
Here I am assigning values in the u.ch
but retrieving from both u.ch
and u.i
,Is it implementation defined ? or I am doing something really silly ?
I know it may seem very beginner to most of other people but I am unable to figure out the reason behind that output.
Thanks,