Alternating without a branch
Suppose you want to achieve the effect of a variable repeatedly alternating between two values
(for example inside a loop) without using a branch. If the variables are just bit patterns such as integers or references (pointers) then you may use bitwise exclusive-or (exor) as follows, and eliminate the branch.
![]()
Of course, the exor of a and b can be precomputed outside the loop. This relies upon exor being not only commutative and associative, but also acting as its own inverse as follows.
![]()
Informally speaking, exor acts as its own inverse; it is both addition and subtraction in its domain.
Soon (after doing some real work) I will say how to alternate cyclically between three different values in a loop, without branching ... this is a little more amusing.