0
Why did this code output 30?
And why is this union is only 4 bytes? https://code.sololearn.com/cwpkT8Fhg76o/?ref=app
2 Antworten
+ 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
+ 1
Shadow Thanks, the design is so weird.