0
#include <stdio.h>
int main()
{  
    union a
    {
       int i;
       char ch[2];
    };
    union a u;
    u.ch[0] = 0;
    u.ch[1] = 2;
    u.ch[2] = 0;
    u.ch[3] = 0;
    printf("%d\n",u.i);   
    return 0;
}

In this program, if the size of integer is given to be 4 bytes, then how is it that the output will be 512? We will see that out of the 4 bytes, the first two bytes will be occupied by 0 and 0. Then why am I getting that as the output?

timrau
  • 22,578
  • 4
  • 51
  • 64
user3845968
  • 113
  • 7
  • Your program causes undefined bahavior; the left two bytes of `u.i` wasn't initialized. – ikh Jul 26 '14 at 09:15
  • 1
    1) `int` is probably 32 bit on your architecture. 2) `ch` is only 2 bytes wide, 3) you assigned `u.ch[1]` three times in a row. – vgru Jul 26 '14 at 09:20

2 Answers2

1

I assume that the code you have posted is in error and that you meant to initialize the other two bytes of the int as in the corrected code below, because otherwise there was very little chance you would get 512 as output.

In this case, because most Intel machines are little-endian, you have set the third most significant byte to 2 and every other byte to 0. Because 2 * 256 = 512, you get 512 as output.

#include <stdio.h>
int main()
{  
    union a
    {
       int i;
       char ch[4];
    };
    union a u;
    u.ch[0] = 0;
    u.ch[1] = 2;
    u.ch[2] = 0;
    u.ch[3] = 0;
    printf("%d\n",u.i);   
    return 0;
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • @ikh, Actually, in this case, it does not matter whether it is `ch[2]` or `ch[4]`, because the `int` will force the memory to be allocated for 4 bytes regardless (we assume `int` is 4 bytes on this platform). – merlin2011 Jul 26 '14 at 09:17
  • @merline2011 But the code is against standard, although assuming `sizeof(int) == 4`, isn't it? – ikh Jul 26 '14 at 09:27
  • @ikh You are most likely correct and it is a one character change so I'll go ahead and change it. In the future though it is better to make such claims only with a reference to a specific part of a specific standard though. – merlin2011 Jul 26 '14 at 09:32
0

Read about endianness. The byte order inside some int is processor dependent.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547