Ternary operation |
In mathematics, a ternary operation is any operation of arity three, that is, that takes three arguments. A ternary operator (sometimes inaccurately referred to as a tertiary operator) is an operator that takes three arguments. A common form found in many programming language is an operator that is used as shorthand for if-then-else statements. The general form is condition op1 : op2 . If condition is true, the statement evaluates as op1 ; otherwise, it evaluates as op2 .
In , and two expressions. It evaluates to the value of the first expression if the controlling expression evaluates to true, and the value of the second expression if the controlling expression evaluates to false. For example:
z = (x > y) x: y;
sets z to the maximum of x and y.
Some corporate programming guidelines list the use of the ternary operator as bad practice because it can harm readability and long-term maintainability. Also, an if statement can be debugged more easily than its ternary counterpart. However, ternary operators are widely used and can be useful in certain circumstances to avoid the use of an if statement, either because the extra verbiage would be too lengthy or because the syntactic context does not permit a statement. For example:
C preprocessor MAX(a,b) (a): (b))
or
for (i = 0; i < MAX_PATTERNS; i++) c_patterns[i].ShowWindow(m_data.fOn[i] SW_SHOW : SW_HIDE);|
|