English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Conditional operator ? :

C++ Operator

Exp1 ? Exp2 : Exp3;

where, Exp1, Exp2 and Exp3 is an expression. Please note the use and position of the colon. The value of the ? : expression depends on Exp1 The result of the calculation.1 is true, then calculate Exp2 The value, and Exp2 The result of the calculation is the value of the entire ? : expression. If Exp1 is false, then calculate Exp3 The value, and Exp3 The result of the calculation is the value of the entire ? : expression.

? is called the ternary operator because it requires three operands, and can be used to replace the following if-else statement:

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

For example, please see the following code segment:

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

The above code can be written as follows:

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. See the following example:

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

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

The value of x: 40

C++ Operator