You can exchange simple if-else code for a single operator – the conditional
operator. The conditional operator is the only C++ ternary operator (working on three
values). Other operators you have seen are called binary operators
(working on two values).
FORMAT:
conditional
Expression ? expression1
: expression2;
** if
the conditional Expression is true,
expression1 executes, otherwise if the conditional
Expression is false, expression
2 executes.
If both the
true and false expressions assign values to the same variable, you can improve
the efficiency by assigning the variable one time:
(a>b) ? (c=25) : (c=45);
can be written as:
c = (a>b) ? 25 : 45;
|