C ++ conditional operator?:
Exp1 ? Exp2 : Exp3;
Wherein, Exp1, Exp2 and Exp3 expression. Please note the use of the colon and location. ?: Expression depends on the value of the calculation result Exp1. If Exp1 is true, then the calculated value Exp2 calculation results and compared the entire Exp2:? Expression. If Exp1 is false, the value Exp3 calculated and compared with the results Exp3 whole:? Expression.
? Is called the ternary operator because it requires three operands, as shown below can be used instead of if-else statement:
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 in the following statement:
var = (y < 10) ? 30 : 40;
Here, if y is less than 10, then var is assigned 30, if y is not less than 10, then var is assigned 40. Consider the following examples:
#include <iostream> using namespace std; int main () { // 局部变量声明 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 results:
value of x: 40