Go to the first, previous, next, last section, table of contents.


Conditional Expressions

A conditional expression is a special kind of expression with three operands. It allows you to use one expression's value to select one of two other expressions.

The conditional expression looks the same as in the C language:

selector ? if-true-exp : if-false-exp

There are three subexpressions. The first, selector, is always computed first. If it is "true" (not zero and not null) then if-true-exp is computed next and its value becomes the value of the whole expression. Otherwise, if-false-exp is computed next and its value becomes the value of the whole expression.

For example, this expression produces the absolute value of x:

x > 0 ? x : -x

Each time the conditional expression is computed, exactly one of if-true-exp and if-false-exp is computed; the other is ignored. This is important when the expressions contain side effects. For example, this conditional expression examines element i of either array a or array b, and increments i.

x == y ? a[i++] : b[i++]

This is guaranteed to increment i exactly once, because each time one or the other of the two increment expressions is executed, and the other is not.


Go to the first, previous, next, last section, table of contents.