[quote user="Devi"][quote user="dicey"]On a related note, not too long ago on a developer's mailing list for a large open-source project that I read, the following C fragment was called "quite elegant"
val -= (val>>31)|1;
Wouldn't you agree? (it replaced the following code if you haven't figured it out by now (and who couldn't tell that the two are equivalent at a glance?))
if (val > 0)
val--;
else
val++;
[/quote] Excellent, both harder to read and slower too, since as far as I can tell it does one extra operation than your version :)
[/quote]Counting operations doesn't give you the relative speed, though. You need to know how long each instruction takes, too.
In this case, one uses an if() statement, thus causing a branch, whereas the other doesn't. Depending on your processor, a branch ranges from no problem at all all the way to a full pipeline stall.
(Not defending the original, though - it's horrible, far from obvious, and only to be used when the code is a known speed bottleneck.)