-1

Declaring variable without initializing it will have a garbage value so in this program I am using a union:

union un
{
    int value;
    char c;
};

int main()
{
    un x;
    x.c = 'A';
    cout << x.value << endl; // garbage: ok
}

above it is ok when printing value it produces a garbage value as long as we didn't initialize it.

but look at this program:

union un
{
    int value;
    char c;
}r;


int main()
{

    r.c = 'A';
    cout << r.value << endl; // 65! as we know the ASCII value of character 'A' is 65
}

so what is the difference between the two program above and why in the second one value gets the value of c?

timrau
  • 22,578
  • 4
  • 51
  • 64
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • 1
    I'm not sure this is a duplicate of the linked question. Yes, it is undefined behavior and so "anything can happen", but the answer actually explains why the values are different. Perhaps the title could be modified to highlight the question's focus on the difference between a global and local value. – wally Jan 27 '17 at 22:36
  • @AnT: IMO that is just a typo. I fixed it. – Al Kepp Jan 30 '17 at 13:46

1 Answers1

2

Your r is a global variable. And these are initialized to zero. The first byte of value is c, the other bytes are zeros.

In contrast, x is a local variable, and those aren't initialied. The first byte of value is c too, but other bytes are like random or garbage, as you call it.

Al Kepp
  • 5,831
  • 2
  • 28
  • 48