?: operator

 
 
 

The ?: operator lets you write a shorthand if-else statement in one statement.

The operator has the form:

condition ? exp1 : exp2;

If condition is true, the operator returns the value of exp1. If the condition is false, the operator returns the value of exp2.

// If $y > 20, $x is set to 10,
// otherwise $x is set to the value of $y.
$x = ($y > 20) ? 10 : $y;
// If $x > 10, print "Greater than", otherwise
// print "Less than or equal".
print(($x > 10) ? "Greater than" : "Less than or equal");

Readability

The following statement sets Balloon’s scaleY attribute to time divided by 2 if time is less than 2, and time multiplied by 2 if time is greater than or equal to 2. (This causes the scaleY attribute to increase slower in the first two seconds than after two seconds.)

Balloon.scaleY = (time < 2) ? time / 2 : time * 2;

This is the same as the following if-else statement:

if (time < 2)
	Balloon.scaleY = time / 2;
else 
	Balloon.scaleY = time * 2;

While the ?; operator saves space and typing, the if...else form is clearly much easier to read. For this reason many programmers avoid using the ?; operator for complex expressions.

Creative Commons License Except where otherwise noted, this work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License