We recently had a lecture in university about programming specials in several languages.
The lecturer wrote down the following function:
inline u64 Swap_64(u64 x) { u64 tmp; (*(u32*)&tmp) = Swap_32(*(((u32*)&x)+1)); (*(((u32*)&tmp)+1)) = Swap_32(*(u32*) &x); return tmp; }
While I totally understand that this is also really bad style in terms of readability, his main point was that this part of code worked fine in production code until they enabled a high optimization level. Then, the code would just do nothing.
He said that all the assignments to the variable tmp
would be optimized out by the compiler. But why would this happen?
I understand that there are circumstances where variables need to be declared volatile so that the compiler doesn't touch them even if he thinks that they are never read or written but I wouldn't know why this would happen here.
In C++, pointer arguments are assumed not to alias (except char*
) if they point to fundamentally different types ("strict aliasing" rules). This allows some optimizations.
Here, u64 tmp
is never modified as u64
.
A content of u32*
is modified but may be unrelated to 'u64 tmp
' so may be seen as nop
for u64 tmp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With