Too much Discussion of the XOR swap trick

Programming
Rambling
Published

June 22, 2024

The following post involves far too much discussion of the XOR swap trick. I suspect many readers already know some of this, so feel free to skip over some early sections if you like!

What does XOR mean?

XOR is short for Exclusive OR (we use the X, instead of EOR, because X is cooler). XOR has a lesser known, less cool friend, Inclusive Or (IOR).

These two names comes from an issue in English (and many other languages), where we use ‘or’ for two different purposes. The difference between these two is when someone talks about “A or B”, are you allowed both A and B, or just one or the other? In maths and computing, where we need to be more exact, we seperate these two cases into XOR (you cannot have both) and IOR (you can have both).

To hopefully make this clearer, let’s consider a couple of real world examples. I decided to pick a couple of examples from the Disney World website. Let’s begin by picking one of the rules of Disney World, you cannot “harass or harm wildlife” – reasonable sounding rule! If you starting kicking a duck while also insulting it, you would be both harassing and harming wildlife. This is clerally an ‘inclusive’ or, if you tried to claim you were not “harrasing or harming wildlife, I’m doing both!”, you would still get kicked out of the park.

On the other hand, over in the Refreshment Corner, the “All-Beef Hot Dog Basket” comes with a “Mandarin Orange or a Small Bag of Chips”. Here, the ‘or’ is exclusive, you can have an orange, you can have chips, but you cannot have an orange and chips! No matter how much you pointed at he person being dragged out of the park for duck harassment and harming, Disney are not going to agree their rules are inconsistent.

How do we know if an ‘or’ is inclusive or exclusive? There are some general rules, but often you just have to know by context. However, because we want to be clear when using computers, we are going to use ‘XOR’ when we mean “A, or B, but not both”.

What is a logical XOR?

What is the XOR bitwise operator?

What is the XOR swap trick?

Usage 1: Swapping local variables

Usage 2: Swapping pointers