C++ Basics
C++ Object Oriented
C++ Advanced
C++ Useful References
C++ Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM
|
C++ Conditional ? : Operator
The ? operator is called a conditional operator and has the following general form:
where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
The ? is called a ternary operator because it requires three operands and can used to replace if-else statements which has the following form:
if(condition){
var = X;
}else{
var = Y;
}
|
For example, consider the following code:
if(y < 10){
var = 30;
}else{
var = 40;
}
|
Above code can be rewritten like this:
var = (y < 10) ? 30 : 40;
|
Here, x is assigned the value of 30 if y is less than 10 and 40 if it is not.
|
|
|