You can use the ? operator to replace if-else statements of the general form:
if (condition) var = expression;
else var = expression;
The ? is called a ternary operator because it requires three operands. It takes the general form
Exp1 ? Exp2 : Exp3
where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the
colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, Exp2 is
evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated
and its value becomes the value of the expression. For example, consider
x = 10;
y = x>9 ? 100 : 200;
In
Thursday, September 18, 2008
The ? Alternative
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment