There is an operator in C + + that runes the only ternary operator in C + +, which is the conditional operator.
Usage:
Cond? Value1:value2;
Brief introduction:
The solution order of this expression is to calculate whether the value of cond is equal to 0, and if it is equal to 0 (that is, false), then return value2(if value2 is an expression, evaluates the expression and returns the result of the calculation), otherwise returns value1 (if value2 is an expression, the value of the expression is evaluated and the result of the calculation is returned).
There are a few things to keep in mind when using ternary operators:
(1) Avoid deep nesting of ternary operators. As the case may be, although it is relatively tall for a program ape, the readability of this code is reduced if you neglect some places that can cause unexpected results.
int value = i > J? i > k? I:k: j > k? J:k;
We need to follow a principle when parsing the expression above: What do ternary operators need? And: As a whole. The first question mark and the penultimate colon match according to the left-to-right principle.
(2) The conditional expression has a relatively low priority, and it is best to enclose the operation of this operator in parentheses. This avoids the unintended consequences of ignoring the operator's precedence, while making the code more readable. Below are a few examples of primer on the list:
cout << (i < J i:j);//ok:prints larger of I and Jcout << (i < j)? i:j;//Prints 1 or 0!cout << i < j? i:j;//error:compares cout to int
There is nothing wrong with the first expression.
The second expression is problematic, he compares the results of I and J as cout operands, outputs 0 or 1, and then evaluates the results of the ternary operator as a condition of the cout operation. If the value of cout is not equal to 0, then the result of returning the ternary operator is I, otherwise J.
This article is from "Home and Everything" blog, please make sure to keep this source http://louis1126.blog.51cto.com/2971430/1679183
Conditional operator (ternary operator)