How to Swap Two Variables Without Using a Temp Variable


With all the high-level languages in widespread use today, it is often easy to forget that at the end of the day, everything boils down to binary: ones and zeroes. This is shielded from us via multiple layers of abstraction. There is nothing wrong with using these abstractions; they have made great modern-day development possible. At the same time, they conceal some of the more intriguing quirks that are inherent in the binary system. This includes bitwise operations, and specifically an operation called a bitwise swap. This is a very efficient operation that can exchange the values of two variables of the same type without using an intermediary variable, and looks like this in C:

Continue reading