go to previous page   go to home page   go to next page

Answer:


If-Else Absolute Value

An if statement can be used to compute absolute values:

if ( value < 0 )
  abs = -value;
else
  abs = value;

This is awkward for such a simple idea. The following does the same thing in one statement:

abs = (value < 0 ) ? -value : value ;

This statement uses a conditional operator. The right side of the = is a conditional expression. The expression is evaluated to produce a value, which is then assigned to the variable, abs.

The conditional operator is used in an expression. It asks for a value to be computed but does not by itself change any variable. In the example, the variable value is not changed. Usually, an assignment operator is used to make a change.


double value = -34.569;
double abs;

abs = (value < 0 )   ?   -value : value ;
      -------------       ------
      1. condition         2.  this is evaluated,
         is true               to +34.569
                      
----
3.  The +34.569 is assigned to abs

The conditional operator is used like this:

true-or-false-condition ? value-if-true : value-if-false

Here is how it works:

  1. The true-or-false-condition evaluates to true or false.
  2. That value selects one choice:
    • If the true-or-false-condition is true, then evaluate the expression between ? and :
    • If the true-or-false-condition is false, then evaluate the expression between : and the end .
  3. The result of evaluation is the value given to the entire conditional expression.

QUESTION 2:

Given

int a = 7, b = 21;

What is the value of:

a > b ? a : b 

(Even though it looks funny, the entire expression stands for a single value.)