Copyright © tutorialspoint.com

C++ Conditional ? : Operator

previous next


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

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:

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

For example, consider the following code:

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

Above code can be rewritten like this:

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 next

Copyright © tutorialspoint.com