A ternary operator is an operator that requires three operands, as opposed to a binary operator that requires two operands and a unary operator that requires just one operand.
C++ has just one ternary operator, the conditional ternary operator:
<boolean expression> ? <expression #1> : <expression #2>;
If the boolean expression evaluates true, the first expression is evaluated, otherwise the second expression is evaluated.
A typical usage of this operator is to return the larger (or smaller) of two values of type T:
template<typename T>
T max (T a, T b) {return a<b ? b : a};
template<typename T>
T min (T a, T b) {return a<b ? a : b};
These are really nothing more than notational shorthand for the following:
template<typename T>
T max (T a, T b) {if (a<b) return b; else return a; };
template<typename T>
T min (T a, T b) {if (a<b) return a; else return b;};
However, because ternary expressions are evaluated, the return value of the expression can be used in more complex expressions:
int a=42, b=0;
// ...
int c = ((a>b ? a : b) = 1);
In the above expression, whichever is the larger of a and b will be assigned the value 1 which will also be assigned to c. Thus a and c become 1 while b remains 0.
Chat with our AI personalities
No. The ternary operator (known as the conditional operator in C++) cannot be overloaded because it is impossible to pass a test operand and two expression operands (either or both of which may be comma-separated) to a function. You can only pass values or references as arguments to a function. Even if it were possible, built-in functions and operators that rely on the conditional operator would likely break. Like all the other operators that cannot be overloaded (sizeof, typeid, ::, . and .*) the results must always be predictable because built-in operators and functions rely on them so heavily.
The conditional operator is also known as ternary operator. It is called ternary operator because it takes three arguments. The conditional operator evaluates an expression returning a value if that expression is true and different one if the expression is evaluated as false.Syntax:condition ? result1 : result2If the condition is true, result1 is returned else result2 is returned.
Compare the first two numbers with the ternary operator. Store the result in a temporary variable. Compare the temporary variable with the third number, again using the ternary operator.
The only "special" operators in C++ are those that cannot be overloaded. That is; the dot member operator (.), pointer to member operator (.*), ternary conditional operator (:?), scope resolution operator (::), sizeof() and typeof().
Selection constructs in C++if...elseswitch/caseconditional ternary operator (?:)
Selection statement: if, switch/case, ternary conditional operator.