# A pointer cast that works at -O0 but silently breaks at -O2

Original title: Type Punning in C and C++

> Hacker News story 49799577 · language: en · submitted 2026-09-22
> Web version: https://zeli.app/story/49799577
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 36 · by [ingve](<https://news.ycombinator.com/user?id=ingve>) · 💬 23
[original](<https://blog.pwkf.org/2026/09/21/correct-type-punning-in-c.html>) · [HN discussion](<https://news.ycombinator.com/item?id=49799577>)

## Summary

Type punning—reinterpreting memory as different types—is essential for serialization and low-level work, but pointer casts are undefined behavior under strict aliasing rules. The author recounts a bug where a float* to uint32_t* cast ran fine at -O0 and silently failed at -O2. The safe alternatives are unions and memcpy, both of which compilers optimize to single instructions.

## Key quote

> The problem is that “works in practice” and “has defined behaviour” are different things.

## HN discussion (23 comments)

### [eqvinox](<https://news.ycombinator.com/item?id=49800348>)

> The example included below "Why C and C++ Differ" is UB in both C and C++ (and says nothing about "why" C & C++ differ).  The article isn't overall wrong but that bit is just...
>
> (Feels a bit like LLM junk, but honestly not sure.)

### [scoopr](<https://news.ycombinator.com/item?id=49800515>)

> I just watched video[0] that argues if you can consteval something, then it must be free of UB, which seems compelling, at least for these lower level helpers.
>
> Unfortunately, it seems memcpy is not constexpr, so cannot be used like this, but std::bit_cast actually works[1] as constexpr, so I think in C++ that would now be the most preferred use. It won't allow the union either.
>
> [0] https://www.youtube.com/watch?v=-LAXqqqX274
>
> [1] https://godbolt.org/z/xGzjTMGvv

### [antiloper](<https://news.ycombinator.com/item?id=49799993>)

> \> The C vs C++ distinction here is genuinely treacherous
>
> What's so genuine about this?

---

## Cite

- Page: https://zeli.app/story/49799577
- Date: 2026-09-22
- Source: blog.pwkf.org (https://blog.pwkf.org/2026/09/21/correct-type-punning-in-c.html)
- Hacker News: https://news.ycombinator.com/item?id=49799577

## Other languages

- zh: https://zeli.app/zh/story/49799577 · markdown: https://zeli.app/zh/story/49799577.md
- ja: https://zeli.app/ja/story/49799577 · markdown: https://zeli.app/ja/story/49799577.md
- ko: https://zeli.app/ko/story/49799577 · markdown: https://zeli.app/ko/story/49799577.md
- de: https://zeli.app/de/story/49799577 · markdown: https://zeli.app/de/story/49799577.md
- es: https://zeli.app/es/story/49799577 · markdown: https://zeli.app/es/story/49799577.md
- ru: https://zeli.app/ru/story/49799577 · markdown: https://zeli.app/ru/story/49799577.md
