C++ Conditional ? : Operator

« Previous Chapter Next Chapter »

The ? operator is called a conditional operator and has the following general form:

Example

Exp1 ? Exp2 : Exp3;
                                        

where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

The ? is called a ternary operator because it requires three operands and can used to replace if-else statements which has the following form:

Example

if(condition){
   var = X;
}else{
   var = Y;
}
                                        

For example, consider the following code:

Example

if(y < 10){ 
   var = 30;
}else{
   var = 40;
}
                                        

Above code can be rewritten like this:

Example

var = (y < 10) ? 30 : 40;
                                        

Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not.


« Previous Chapter Next Chapter »

Have Any Suggestion? We Are Waiting To Hear from YOU!

Your Query was successfully sent!