Is type punning safe in Odin?

Do I understand this post correctly, that Odin allows type punning and has (by default[1]) no strict aliasing rules?

Relevant part of Bill’s post:

[…] My philosophy for Odin was that you want to opt-in to the generally unsafe “optimizations” (when possible) rather than them be opt-out, especially when the language/compiler does not enforce stricter semantic analysis. […]

Do I interpret this correctly that Odin allows[1:1] type punning via both, pointer casts & #raw_union?

In other words:

  • Can I happily cast any pointer type to any another pointer type and rely on the Odin compiler to behave as if I compiled the equivalent C/C++ code with -fno-strict-aliasing?
  • Likewise, can I use type punning with #raw_union and happily access any field independent on which field was previously written to it?

I am aware that for many real-world usecases the transmute operator is what I probably want. But I it’s just nice to have straight forward type-punning in my toolbox and treat bytes just as bytes with interpretation, not part of some abstract objects.


  1. as long as I don’t use #no_alias ↩︎ ↩︎

  • Odin does effectively have -fno-strict-aliasing.
  • Prefer transmute over #raw_union because it is easier in most cases. You can use it, but in Odin, it’s rarely the prefer approach. You can think of transmute as memcpy because it also cares about the alignment too.
1 Like