|
Question Mark Operator
- It is a conditional statement
– allow for selective execution of portions of the program
according to the Boolean expression
- similar to if statements
if (a > b)
{
max = a;
}
else
{
max = b;
}
- consider the above if-else statement
- the condition is a Boolean
expression – must evaluate to a true or false
- if the condition is true,
the statements in the curly brackets after the ‘if’
statement is run
- if the condition is false,
the statements following the ‘else’ is run
- the following statement
performs the same functions as the if-else statement
max = (a > b) ? a : b;
- question mark operator was
devised as a shortcut for if-else statements with a single condition
- it is a statement in which
one of the two values – a or b – after the “?”
is returned
- the value returned is
dependent on the conditional test, (a > b)
- if the condition is true,
the first value is returned
- if the condition is false,
the second value is returned
General formula
Variable
= (Boolean expression) ? value if true : value if
false;
|