It's been a long time since I've done any C programming (the only C I ever really did was in school 10+ years ago) and I've never done it outside of school. I figure since I look at and study languages that are pretty esoteric, it's only fair to throw in a language that is really widely used. It should make my Objective-C better (which probably isn't saying much). It also gives me a chance to go "a little closer to the metal" I guess. Hey look, a Bus Error!
Anyway, one of the things that I love/hate about C are the little tricks that people often use. Sometimes they're really fun but often they take a bit of thinking to understand if you're not familiar with them. One of those that I ran across again was swapping values without a temp variable.
How Normal People Swap ValuesThe simplest way of swapping two values is ususally accomplished using a temp variable to hold one of the values for a moment.
And Another WayBut you can accomplish the same thing using an Exclusive Or (XOR) operation.
To review bitwise operations:
& AND 0101 (5) 1100 (12) ---- & 0100 (4)
| OR 0101 (5) 1100 (12) ---- | 1101 (13)
^ XOR 0101 (5) 1100 (12) ---- | 1001 (9)
The ^= just combines the XOR with an Assignment. Now isn't that totally intuitive? Yeah, not to me either. Technically once you know this piece of trivia, you don't really need to think about it. You'll just recognize the pattern and understand what's going on. But understanding why it works is probably a good thing.
So, I just came up with an example that shows what's happening:
What are some of the principles in why this works?:
XOR is a reversible binary operation.
This isn't a proof of any sort, but hopefully it will help you understand why it actually works. If you want even more of an explanation, and a proof, check out the article on Wikipedia: XOR Swap Algorithm