-3

I was expecting the output to look like: 10 20 10 20

But the output came like this: 10 20 20 20

What is happening behind the code?

#include <iostream>

using namespace std;

typedef struct sdata{
    int a;
    int b;
    union udata{
        int a;
        int b;
    }u;
}Data;

int main()
{
    Data s;
    s.a = 10;
    s.b = 20;
    s.u.a = 10;
    s.u.b = 20;
    cout << s.a << " " << s.b << " " << s.u.a << " " << s.u.b;
    return 0;
}
timrau
  • 22,578
  • 4
  • 51
  • 64

1 Answers1

1

Unlike a struct, a union can only hold one member at a time. Each member starts at the same memory address, so writing to one affects the other.

In this case your union has two fields of type int. So if you set one than the other will contain exactly the same value. So when you set s.u.b to 20 it also sets s.u.a to that value as well.

dbush
  • 205,898
  • 23
  • 218
  • 273