Ahh, yes . . . CS instructors have been giving extra credit for "discoveries" of this swap algo for years! And yes, GCC will usually recognize when a swap occurs and do it in a machine-specific optimized fashion.
As far as the XOR swap being less readable, I respectfully disagree. Given that GCC will produce the same output regardless, I almost always use the XOR algo, simply because temporary variables are needless cruft in my beautiful code! *grin*
I've got good news, and I've got bad news: The universe is merely a figment of my imagination. Now are you ready for the bad news?
I liked your bit of code. Out of curiosity I created the exact same chunk of code using a temporary variable instead, and I compiled them both using GCC with no optimization. The code without the temp variable actually created 5 more lines of assembly code. Then, I compiled them both with an optimization level of 3, and the assembly output was exactly the same.
As far as the XOR swap being less readable, I respectfully disagree. Given that GCC will produce the same output regardless, I almost always use the XOR algo, simply because temporary variables are needless cruft in my beautiful code! *grin*
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
Still neat, though.
Keep this one in mind for hardware programming with a latch or flip-flop.