C++ ?: Detailed explanation of the usage of conditional operator (ternary operator)

Conditional operators are powerful and unique, providing a shorthand way to express simple  if-else  statements. This operator consists of a question mark (?) and a colon (:), and its format is as follows:

expression? expression: expression;

The following are examples of statements using conditional operators:

x < 0 ? y = 10 : z = 20;

This statement is called a conditional expression, and it consists of three subexpressions, separated by question marks? and colon:. These three expressions are: x<0, y = 10 and z = 20.

The conditional expression above performs the same operation as the following if-else statement:

if (x < 0)
    y = 10;
else
    z = 20;

The part of the conditional expression before the question mark is the condition to be tested. This is like an expression in parentheses of an if statement. If the condition is true, the statements between ? and : are executed; otherwise, the part after : is executed. If you find it helpful, you can place parentheses around the subexpression, like this:

(x < 0) ? (y = 10) : (Z = 20);

Figure 1 illustrates the roles played by the three subexpressions.


 

The role of the three subexpressions in the conditional operator


Figure 1 The role of the three subexpressions in the conditional operator

<

Guess you like

Origin blog.csdn.net/m0_73557158/article/details/133409177