Wednesday, December 8, 2010

Ternary Operator?

The ternary operator is a shorthand for the classic if-else.  Its advantage is line-saving if you really enjoy writing compact code.

The syntax for the ternary operator is:

<condition>?<statement>:<statement>

where the first statement is executed if the condition evaluates to true, or else the second statement is executed.

For example: (code in Python)

print('There'+((n==1)?' is ' :' are ')+n+' item'+(n!=1)?'s':'')

For n = 0, the statement would read "There are 0 items"
For n = 1, the statement would read "There is 1 item"
For n = 2, the statement would read "There are 2 items"

Ternary operators allow inline decision-making at the cost of readability, so use them wisely.

No comments:

Post a Comment