C++ Conditional Operator ? :
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Note the use and position of the colon. The value of the ? : expression depends on the result of Exp1. If Exp1 is true, then the value of Exp2 is evaluated and becomes the value of the entire ? : expression. If Exp1 is false, then the value of Exp3 is evaluated and becomes the value of the entire ? : expression.
The ? is known as the ternary operator because it takes three operands and can be used to replace an if-else statement like the one shown below:
if(condition){
var = X;
}else{
var = Y;
}
For example, consider the following code:
if(y < 10){
var = 30;
}else{
var = 40;
}
The above code can be written as:
var = (y < 10) ? 30 : 40;
Here, if y is less than 10, then var is assigned the value 30; otherwise, var is assigned the value 40. Consider 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