Conditional Operator

  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;

 



if (a>b)
{
       c=25;
 }
 else
{
       c=45;
 }


can be replaced with
(a>b) ? (c=25) : (c=45);

The question mark helps the statement read as follows:
"Is a greater than b?  If so, put 25 in c.  Otherwise, put 45 in c."



Return to Topic Menu | Computer Science Main Page | MathBits.com | Terms of Use