C++ Conditional Operator ? :
Exp1 ? Exp2 : Exp3;
Here, Exp1, Exp2, and Exp3 are expressions. Note the use and position of the colon. The value of the ?: expression depends on the evaluation of Exp1. If Exp1 is true, Exp2 is evaluated, and Exp2's result becomes the value of the entire ?: expression. If Exp1 is false, Exp3 is evaluated, and Exp3's result becomes the value of the entire ?: expression.
? is called the ternary operator because it requires three operands and can be used in place of an if-else statement, as shown below:
if(condition){
var = X;
}else{
var = Y;
}
For example, consider 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, var is assigned 30; if y is not less than 10, var is assigned 40. See the example below:
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 code above is compiled and executed, it produces the following result:
value of x: 40
C++ Operators