charlie_chan <[EMAIL PROTECTED]> wrote:
> ...The ? operator is used to replace statements such as:
> 
> if(condition) var = exp1;
> else var = exp2;
> 
> The general form of the ? operator is
> 
>     var = condition ? exp1: exp2;

It can be used outside of assignment. Indeed, you are more
likely to find the conditional operator used in function
macros that return a value, e.g.

  #define MIN(a,b)  ((a) < (b) ? (a) : (b))

This macro can't be done with an if/else statement. [Not
without compiler extentions.]

> Here, condition is an expression that evaluates to true or
> false.  If it is true, var is assigned the value of exp1.
> If it is false, var is assigned the value of exp2.

Your description is not literally true.

Before running this program, try to guess what the output
is...

  #include <stdio.h>
  
  int main(void)
  {
    if ( (1 ? -1 : 1u) < 0 )
      puts("-1 is negative, everyone knows that!");
    else
      puts("huh?!");
  
    return 0;
  }

The explanation for the output is because, if the
result expressions have arithmetic type then
arithmetic promotions are applied. If one operand
has unsigned type (as 1u has) and the other has
int type (as -1 does), then the int expression is
converted to unsigned int. So -1 becomes UINT_MAX.

> The reason for the ? operator is that a C compiler can
> produce more efficient code using it instead of the
> equivalent if/else statement.

No. The operator exists as syntactic sugar.

-- 
Peter

Reply via email to