4 ms·
This could prevent some useful optimizations. The following can be a single rotate instruction but only when relying on undefined behavior of shifts (otherwise
by praptak 8y ago
This could prevent some useful optimizations. The following can be a single rotate instruction but only when relying on undefined behavior of shifts (otherwise the code has to produce zero for i outside the sensible range)
(n << i) | (n >> (sizeof(n) - i))
So, does it fall under "demons out of your nose"?
- tomerv 8y agoI'm the article's suggestion, this could still be a single instruction, as long as it's documented behavior.
- mar77i 8y agodidn't you want to multiply your sizeof n by CHAR_BIT?
- pg314 8y agoOf course that code is broken (relies on undefined behavior) when i is zero, which is a totally reasonable input for a rotate function. A nice illustration of the pitfalls of undefined behavior. You can find a correct implementation in a blog post by John Regehr [1]. [1] https://blog.regehr.org/archives/1063 https://blog.regehr.org/archives/1063
- MaxBarraclough 8y agoI don't really buy the idea that invoking undefined behaviour is ok so long as you know it happens to work on your platform. If that disaster really does boil down to one instruction, I'd hope the compiler would expose an intrinsic. Doing that kind of thing isn't so evil if you're careful to include a compile-time assert that will break the build (or perhaps 'failover' to safe code) if you try to compile on anything but your exact compiler and for anything but your exact target platform, but even so, I've never seen an appropriate time to deliberately invoke UB like that.