C++ Conditional Operator ? :

C++ Operators

Exp1 ? Exp2 : Exp3;

Here, Exp1, Exp2, and Exp3 are expressions. Note the use and placement of the colon. The value of the ? : expression depends on the result of evaluating Exp1. If Exp1 is true, then Exp2 is evaluated, and the result of Exp2 becomes the value of the entire ? : expression. If Exp1 is false, then Exp3 is evaluated, and the result of Exp3 becomes the value of the entire ? : expression.

? is called the ternary operator because it requires three operands, and can be used to replace if-else statements as shown below:

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

For example, take a look at the following code:

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

The code above can be written as the following statement:

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

Here, if y is less than 10, then var is assigned the value 30; if y is not less than 10, then var is assigned the value 40. Take a look at the following example:

Example

#include <iostream> using namespace std; int main () { // Local variable declaration int x, y = 10; x = (y < 10) ? 30 : 40; cout << "value of x: " << x << endl; return 0; }

When the above code is compiled and executed, it produces the following result:

value of x: 40

C++ Operators

other extensions