Samuel
Samuel

Reputation: 851

memory mapping for Union

union Data {
    int a;
    double b;
    Data(){
        a = 1;
        b = 0.5;
    }
};

int main(){

    Data udata;
    udata.a = 999999999;
    cout << udata.a << "\t" << udata.b << endl;
    return 0;
}


result: 999999999       0.5

I knew a and b are mapped to the same memory location, but why b is still equal to 0.5 after assigning 999999999 to a.

Upvotes: 1

Views: 170

Answers (1)

Rohan Bari
Rohan Bari

Reputation: 7726

The reason is that their different data-types have separated them. Your union code defines a as integer & b as double and b's value is still unchanged even after having same memory addresses. If you set either a as double or b as integer, you'll get the values changed together..

Look at the following:

union Data {
    int a;
    int b; // changed double to int

    Data() {
        a = 1;
        b = 0.5;
    }
};

Hope it helps you understand.

Upvotes: 1

Related Questions