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

The output is: 0 2
Why is the output 0 2, when it should be some garbage value?

Sagar
  • 273
  • 1
  • 3
  • 12

1 Answers1

1

I am not sure why you expect the compiler to generate garbage for you, when you have just told it to initialize to i to 512. The least two significant bytes of 512 are 0 and 2.

Implementation-specific behavior is not the same as garbage.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • I have initialized i to 512, then how are the values of z.ch[0] and z.ch[1] becoming 0 and 2? According to me it should be garbage values since we are just initializing i and not ch[]. If I am wrong please explain what actually happens? I have just learned about unions. – Sagar Jun 24 '14 at 06:42
  • 1
    @Sagar, The members of a `union` share the same memory address. When you initialize `i` and read `ch`, you are basically interpreting the 4 bytes you just wrote into `i` as individual bytes using `ch`. – merlin2011 Jun 24 '14 at 06:51