C++ Programming/Operators/Conditional Operator

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

[edit] Conditional Operator

Conditional operators (also known as ternary operators) allow a programmer to check: if (x is more than 10 and eggs is less than 20 and x is not equal to a...).

Most operators compare two variables; the one to the left, and the one to the right. However, C++ also has a ternary operator (sometimes known as the conditional operator), ?: which chooses from two expressions based on the value of a condition expression. The basic syntax is:

 condition-expression ? expression-if-true : expression-if-false

If condition-expression is true, the expression returns the value of expression-if-true. Otherwise, it returns the value of expression-if-false. Because of this, the ternary operator can often be used in place of the if expression.

  • For example:
int foo = 8;
std::cout << "foo is " << (foo < 10 ? "smaller than" : "greater than or equal to") << " 10." << std::endl;

The output will be "foo is smaller than 10.".

TODO

TODO
Note the short-cut semantics of evaluation. Note the conditions on the types of the expressions, and the conversions that will be applied if they have different types. Note that code that discards the value of the conditional expression can be more clearly written using an if statement.