Tuesday, April 17, 2007

Toggle The Toggler

We all use them, different places in our code, toggling variables.
And there are many ways to achieve the same results.


My first toggle looked like that. This toggles between 1 and -1.
a *= -1;

It then evolved to:
a = a XOR 1; // or a = a ^ 1 in Java

I also started using the modulus operator:
a = (a + 1) % 2;

Then I liked the modulus operator so much, that I started using it to toggle between three, four or N values:
a = (a + 1) % 4;