answersLogoWhite

0

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.

User Avatar

Wiki User

10y ago

Still curious? Ask our experts.

Chat with our AI personalities

JudyJudy
Simplicity is my specialty.
Chat with Judy
SteveSteve
Knowledge is a journey, you know? We'll get there.
Chat with Steve
RossRoss
Every question is just a happy little opportunity.
Chat with Ross
More answers

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.

User Avatar

Wiki User

12y ago
User Avatar

A conditional operator (? : ) is called the ternary operator

User Avatar

Wiki User

14y ago
User Avatar

Add your answer:

Earn +20 pts
Q: Which operator is called ternary operator?
Write your answer...
Submit
Still have questions?
magnify glass
imp