1//(expression 1) ? expression 2 : expression 3
2//If expression 1 evaluates to true, then expression 2 is evaluated.
3 int x, y = 10;
4
5 x = (y < 10) ? 30 : 40;
6 cout << "value of x: " << x << endl; //prints 40
7
8
1//one ternary operator
2statement ? if-true-do-this : if-false-do-this;
3//if-statement version
4if(statement){
5 if-true-do-this;
6}else{
7 if-false-do-this;
8}
9
10
11//nested ternary operator
12statement-1 ? if-true-do-this-1 : statement-2 ? if-true-do-this-2 : if-false-do-this-2;
13//if-statement version
14if(statement-1){
15 if-true-do-this-1;
16}else {
17 if(statement-2){
18 if-true-do-this-2;
19 }else{
20 if-false-do-this-2;
21 }
22}
23
1x = condition ? expression1 : expression2
2
3// Example:
4double x = 1 > 0 ? 10 : 20; // put any value