Friday, April 6, 2007

How To Write Out Much Shorter And Easier If / Else Statements

Sometimes you might wish to have an easy alternative to the tedious task of writing (often repetitive) if and else statements. If and else statements can eventually crowd your code with excessive lines. With this shortcut, you can express entire if and else blocks, and even be able to assign a variable a value based on whether a condition is true or not; all in one line. The solution is the called the ternary or conditional operator. It' called the "ternary" operator because it performs operations of 3 operands (an operand is simply data that's effected by an operator). The syntax for this particular operator is as follows:

//Variable = ( (condition) ? true actions: false actions)
Speed = (guy._x > 500 ? 0: 5);

Observe the example using the assignment of the “Speed” variable. That one line means all of this: “If guy._x>500 evaluates to TRUE, assign Speed to 0. Else, assign it to 5.”

If this syntax may confuse you a great deal at first, don't fret. Many programmers have difficulty with this particular operator as its syntax is hard to understand to the untrained eye.