Why?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why??

I faced the below problems in my solo learn challenge can someone explain the reason behind the answer? https://www.sololearn.com/post/331460/?ref=app

17th Apr 2020, 5:51 PM
Akash
Akash - avatar
5 Answers
+ 1
Well, this is from my own understanding as well, but I can try. When you store a value in a union variable, what is actually stored is the binary value. What the binary represantation looks like is affected by what kind of data you are storing. When you retrieve the value through a member of the union, that binary value is interpreted as the data type of the member you are accessing. Different data types have different encodings on the binary level, for example the interpretation of a float differs from the interpretation of an integer, that is why accessing inactive members is usually a terrible idea. But in your case, you have two integers. If you write a value to one member and then access the other, inactive member, what happens is exactly what would happen if you were to access the active member: The binary value is interpreted as an integer and returned. A valid integer can be formed either way, and it is the same you last wrote into the union because the data type is the same.
19th Apr 2020, 10:35 PM
Shadow
Shadow - avatar
+ 4
Accessing an inactive union member is not undefined behaviour in C, as one might expect. In such a case, the appropriate part of the binary represantation of the current value is reinterpreted as the requested data type and then returned. Since both union members are integers in your example, no reinterpretation is required, and you get the exact value that was stored in the union last. For a detailed answer taking the C Standard into account, see: https://stackoverflow.com/questions/11373203/accessing-inactive-union-member-and-undefined-behavior
17th Apr 2020, 6:36 PM
Shadow
Shadow - avatar
+ 1
It might be more correct to say because both are the same data type, you get the same value back, after all there is only one real value to overwrite for all members; but basically yes.
20th Apr 2020, 8:47 PM
Shadow
Shadow - avatar
0
Shadow , Ok that was a mouthful. Since I have just started learning C, could you kindly simplify the answer.
18th Apr 2020, 5:48 PM
Akash
Akash - avatar
0
Shadow ok, so in a way because both are same data type the value is getting overwritten on the inactive member.
20th Apr 2020, 5:34 PM
Akash
Akash - avatar