Hacker News new | ask | show | jobs
by genocidicbunny 1779 days ago
Type punning is not undefined, it's implementation defined in C. In practice, every major C compiler will be fine with type punning, though it may disable some optimizations.

The story is different in C++, but in practice many compilers support it the same as in C. Especially for games, where VC++ (PC, Xbox) and Clang (PS4/PS5) are the most commonly used compilers, it also works as expected. The trick is to only use type punning for trivial structs that don't invoke complications like con/de-structors or operators. The GP's example of a Vec3 struct that puns float x,y,z with float[3] is a very common one in games.

1 comments

Something being very common and a very common source of portability issues isn't exactly contradictory. Its a bad idea, and it is outright being taught in modern game programming courses that its a bad idea, but common in older guides, specifically because it caused so many problems. Im pissed at this specific construct because I got it handed to me in a huge game library and had to spent a long time figuring out why it wasn't working in rare, but important cases.
But my point is that on the platforms that matter, it's not really a source of portability issues, and not a problem. For gamedev, anything outside of VC++ and Clang are niche and thus largely ignored.