my code is as follows:-
#include<stdio.h>
main() {
union a {
short int x;
char y[2];
};
union a e;
e.y[0] = 3;
e.y[1] = 2;
printf("%d\n%d\n%d\n", e.y[0], e.y[1], e.x);
return 0;
}
It gives output as
3
2
515
i didn’t understand that how this 515 comes?
Since I wanted an excuse for ASCII art…
Declaring the
unionlets you choose how to interpret its data. In your case, either as anunsigned shortor achar [2]. Both of these are 2 bytes long, so your union will refer to a 2-byte section of memory, thusly:Now you decide to interpret your union as a character array:
Then you interpret it as an
unsigned short:You’re on a little-endian system (as @Oli noted), meaning the least-significant byte is stored first in memory. Which means that when your code looks at an
unsigned short, it thinks0x03is the least-significant byte.So your 2-byte unsigned short is interpreted as
0x0203. And0x0203hex is515decimal.That comment was interesting enough to put in the answer for clarity, I think.
Let’s say we do this:
What’s inside? Break it down:
intis 4 bytes,char [2]is 2 bytes, so theunionis 4 bytes long to store the largest datatype.512is0x00000200in hex. So store that integer little-endian and you have:So
e.xis 512.e.y[0]is 0 ande.y[1]is 2