Ternary Operator
Ternary operator is a compact conditional assignment.
It serves to set a value of a variable depending on a boolean expression or a boolean variable.
a = b ? c : d;
The expression above is same as:
if ( b ) { a = c; } else { a = d; }
The a
, c
and d
variables
must be of the same data type (or type of c
and d
must be convertible to type of a
using automatic conversion).
The b
variable is boolean
.
b
, c
or d
do not have to be variables.
They may be constants or expressions.
a
has to be a variable.
For example, you can use a ternary operator to assign minimum of c
and d
into a
in a compact way:
a = c < d ? c : d;