I've been reading up on the strict aliasing rules over the last week or so and ran into this article: Understanding C/C++ Strict Aliasing.
The article goes through several ways two swap the halves of a 32-bit integer, giving both good examples and ones that violate the strict aliasing rule. I'm having trouble understanding one of the examples, though.
This code is described as broken.
uint32_t
swaphalves(uint32_t a)
{
a = (a >> 16) | (a << 16);
return a;
}
The reason given is:
This version looks reasonable, but you don't know if the right and left sides of the | will each get the original version of
a
or if one of them will get the result of the other. There's no sequence point here, so we don't know anything about the order of operations here, and you may get different results from the same compiler using different levels of optimization.
I disagree. This code looks fine to me. There is only one write to a
in the a = (a >> 16 | (a << 16);
line, and I expect that both reads of a
take place before that write. Further, there are no pointers or references and no incompatible types.
Am I missing a strict aliasing violation in this code, or is the article incorrect?
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