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

Why did this code output 30?

And why is this union is only 4 bytes? https://code.sololearn.com/cwpkT8Fhg76o/?ref=app

13th Aug 2020, 12:47 PM
Jax Young
Jax Young - avatar
2 Answers
+ 5
All members of a union share the same memory space, so the union itself just allocates as much space as its biggest member requires, which in this case is four bytes for an integer, hence the size. Since both integers share the same memory space, you will get the last value written to the union regardless of which member you access, but it only works because both have the same type. In reality the explanation is a bit more complex, here you can find a more detailed answer to it: https://stackoverflow.com/questions/11373203/accessing-inactive-union-member-and-undefined-behavior
13th Aug 2020, 1:17 PM
Shadow
Shadow - avatar
+ 1
Shadow Thanks, the design is so weird.
13th Aug 2020, 3:11 PM
Jax Young
Jax Young - avatar