The ? operator

c/c++ contains a very powerful and convenient operator that replaces certain statement of if-than-else form.

the ternary operator ? takes th egeneral form exp1 ? exp2 : exp3;

 where exp1,exp2 and exp3 are Expressions.

working: exp1 will be evaluated if it is true, exp2 is evaluated and becomes the value of th eexpression.

If exp1 is false, exp3 is evaluated and its value becomes the value of th eexpression.

 example:  x = 10;
       y = x > 9 ? 100 : 200;
'y' is assigned the value 100. if 'x' had been less than 9, y would have received the value 200. 
The same code written using the if-else statement is
       x = 10;
       if(x>9)
             y=100;
       else y = 200;
 

Posted on by