Dec 25, 2009

Quick Tip: light switch effect

Here's a quick tip for novice programmers. Every time you want to create a "light-switch" effect for toggling a parameter on and off, or should I say true or false, 0 or 1, ... You can simply do it by typing:
p ^= 1;
This is a binary-safe Exclusive-OR assignment operator. First, it computes the value of p XOR 1 (p = p ^ 1) and then stores that value in p. If we look at the truth table of exclusive-or (XOR)

a

b

a XOR b

0

0

0

0

1

1

1

0

1

1

1

0

We see that if our b variable is 1 (true) the result of a ^ 1 (a XOR 1) is exactly the opposite of a. All in all, this operation is simply a shortcut for these assignments:
p = p ^ 1;

p = !p;

p = p ? false : true;

if(p) p = false; else p = true;

So if you want to toggle something ON and OFF, let's say when a user clicks a button, this method is extremely short and useful.

No comments: