I am currently wondering about the rationale behind the strict aliasing rule. I understand that certain aliasing is not allowed in C and that the intention is to allow optimizations, but I am surprised that this was the preferred solution over tracing type casts when the standard was defined.
So, apparently the following example violates the strict aliasing rule:
uint64_t swap(uint64_t val)
{
uint64_t copy = val;
uint32_t *ptr = (uint32_t*)© // strict aliasing violation
uint32_t tmp = ptr[0];
ptr[0] = ptr[1];
ptr[1] = tmp;
return copy;
}
I might be wrong, but as far as I can see a compiler should perfectly and trivially be able to trace down the type casts and avoid optimizations on types which are casted explicitly (just like it avoids such optimizations on same-type pointers) on anything called with the affected values.
So, which problems with the strict aliasing rule did I miss that a compiler can't solve easily to automatically detect possible optimizations)?
double
orlong
must be on an 8-byte boundary lest your process be killed via something likeSIGBUS
? That's not technically a strict aliasing issue, but it touches on a lot of the same underlying issues. – Worcestershireuint64_t
is almost by definition suitably aligned foruint32_t
@AndrewHenle, so not an issue here for sure. – Unbar