Alternating three ways without branching
Suppose you want a variable to cycle between three different values in a loop, like this.

If this code is executed in a loop, then x will alternate between the values a, b, and c repeatedly. But how may we achieve the same effect without any branching? Tricky...here's a little scheme I've cooked up to do just that. It cheats by using two variables x and y. The mysterious "plus-in-a-circle" operation is bitwise exclusive-or (exor).
First, before the loop starts, initialize x and y, and precompute the magic constant s as follows.

Then inside the loop execute the following non-branching code.
![]()
Note that x cycles between the following three values, because of the self-inverse property of exor (see Alternating without a branch).

So if we exor x with the magic constant s we get a value that cycles between a, b, and c, because of the self-inverse property of exor, once again.
There's a secret connection between this scheme and the Fibonacci numbers...
Comments
I like this very much. It reminds me that it is easy to forget the mathematical foundations of the code we write. I write code for limited memory embedded processors as a hobby and this seems like it would be a very useful alternative to a branch instruction sequence.
I also just attended a lecture on Nvidia's CUDA architecture and this seems like a good optimization technique for certain operations. The architecture performs best when many threads are performing exactly the same operation, and this might help avoid the problem of the instruction sequence diverging because of the branch instructions.
Posted by: Nathan Johnston | April 15, 2008 03:04 PM