The conditional operator   ? :

  • The conditional operator (denoted as:   ? : ) is the only ternary (3 operands) operator in C (and in Java).

  • Syntax of the conditional operator:

     expr1 ? expr2 : expr3 
    
     Effect:
    
        if  expr1  is  true  (i.e.: non-zero)
           return: expr2
        else
           return: expr3  

Common usage of the conditional operator   ? :

  • The conditional operator is commonly used to find the maximum (or minimum) of 2 values:

      max = (a > b) ? a : b ; 
    
      min = (a < b) ? a : b ; 

  • It is common to find C programs that use the following macros to compute the the maximum or the minumum of 2 values:

      #define  max(a,b)   ( ((a) > (b)) ? (a) : (b) )
    
      #define  min(a,b)   ( ((a) < (b)) ? (a) : (b) )

    ( Every possible sub-expression is put between brackets to avoid errors caused by operator priorities)