Hack of the day: Alternating among two values
December 31, 2010
During game development you often need a variable that switches between two values with each call/loop/frame. Here is a short example:
const int a = 38;
const int b = 21;
int x = 0;
// [ ... ]
if (x == a) {
x = b;
} else {
x = a;
}
In C/C++ (and also other languages like Java, PHP, ActionScript…), you also often see the following shorter syntax, that does the exact same thing:
const int a = 38; const int b = 21; int x = 0; // [ ... ] x = (x == a) ? b : a;
But a better and more efficient way to code this is:
const int a = 38; const int b = 21; int x = b; // make sure x is initialised with one of the constants // [ ... ] x = a + b - x;
This is faster because the compiled code requires no instructions for the if statement.
If you want to switch between true and false, you can use:
bool x = true; // [ ... ] x = !x;
If you want to switch between a negative and positive value, you can use:
int x = 10; // [ ... ] x *= -1;
I knew the others but not this one: x = a + b – x Makes sense though. Thanks!
In the last one you can also do this in some languages:x = -x;