1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

union problem

Discussion in 'C' started by manish007g, Aug 22, 2012.

  1. manish007g

    manish007g New Member

    Joined:
    Aug 22, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    int main()
    {
    union a
    {
    int i;
    char ch[2];
    };
    union a z={512};
    printf("%d %d",z.ch[0],z.ch[1]);
    return 0;
    }

    Output is 0 2 but how? please explain ..
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Think how 512 is stored in memory. Did you get 0x02 and 0x00 (thus forming the 16-bit number 0x0200)? That's where the 0 and 2 come from.

    Best not rely on this though. This is going to be very compiler and platform dependent - completely unportable.
     

Share This Page