union
{ int i;
bool b;
} x;
x.i = 20000;
x.b = true;
cout << x.i;
It prints out 19969. Why does it not print out 20000?
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.
A
unionis not astruct. In aunion, all of the data occupies the same space and can be treated as different types via its field names. When you assigntruetox.b, you are overwriting the lower-order bits of20000.More specifically:
20000 in binary: 100111000100000
19969 in binary: 100111000000001
What happened here was that you put a one-byte value of 1 (00000001) in the 8 lower-order bits of 200000.
If you use a
structinstead of aunion, you will have space for both anintand abool, rather than just anint, and you will see the results you expected.