Search code examples
cunion-types

About union in C


union a
{
    int i;
    char ch[4];
};
void main()
{
    union a u;
    u.ch[0]=3;
    u.ch[1]=2;
    u.ch[2]=0;
    u.ch[3]=0;
    printf("%d %d %d",u.ch[0],u.ch[1], u.i);
}

Ouput : 3 2 515

Why i get 515 for u.i Can anyone please explain me about this?


Solution

  • Check this, the system will allocate 2 bytes for the union. The statements u.ch[0]=3,u.ch[1]=2store data in memory as given below.

    Image

    To be more clear

    u.ch[0]=3;
    u.ch[1]=2;
    

    Now u.i is calculated as

    (2)(3) in binary form which is equal to 515.
    
    (2) --> 00000010; (3) --> 00000011
    
    (2)(3) --> 0000001000000011 --> 515.
    

    Hope this will help you.