Simple question about this piece of code:
union MyUnion
{
int a;
int b;
};
union MyUnion x, y;
x.a = 5;
y.b = 2;
y.a = 3;
x.b = 1;
int c = (x.a - y.b) + (y.a - x.b);
Can someone explain why the value of c is 0 here ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can only access the last-written field of a union. This code violates that, and thus invokes undefined behavior.
In essence, since both MyUnion.x and MyUnion.y share the same memory, you can probably replace the code with:
This simplifies down to
c = (1 - 3) + (3 - 1), which is-2 + 2or0.Note that this is simply based on the observation that this is how compilers typically seem to implement unions, and it explains the observed behavior. It’s still undefined though, and you should be careful with code like this.