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
", 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 am I 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.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…