4 ms·
In C, yes, type-punning with union is valid. However, in C++, it is considered undefined behavior and may get removed by the compiler if it sees fit.
by physguy1123 10y ago
In C, yes, type-punning with union is valid. However, in C++, it is considered undefined behavior and may get removed by the compiler if it sees fit.
- colin_mccabe 10y agoThanks for the clarification. Do the new C++ standards explicitly discuss this anywhere?
- physguy1123 10y agoThere's this stackoverflow qanswer: http://stackoverflow.com/questions/11373203/accessing-inactive-union-member-undefined-behavior http://stackoverflow.com/questions/11373203/accessing-inacti... where answers try to distill the standard into something legible by humans. Unsurprisingly, they come to different conclusions. The overall interpretation in some situations, if you look at things just right, you can do type punning in C++. But it's pretty risky since you're a LOC away from the compiler deleting your function. Or, you can't really do it at all safely. Which I would conclude from the above anyways.