How do I use the conditional operator?

It works like this:

(condition) ? true-clause : false-clause

It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example).

For example:

bool Three = SOME_VALUE;
int x = Three ? 3 : 0;

is the same as

bool Three = SOME_VALUE;
int x;
if (Three)
    x = 3;
else
    x = 0;

It works like this:

expression ? trueValue : falseValue

Which basically means that if expression evaluates to true, trueValue will be returned or executed, and falseValue will be returned or evaluated if not.

Remember that trueValue and falseValue will only be evaluated and executed if the expression is true or false, respectively. This behavior is called short circuiting.


In c++ there's no actual if part of this. It's called the ternary operator. It's used like this: <boolean statement> ? <result if true> : <result if false>; For your example above it would look like this:

C = A > B ? A : B;

This article on wikipedia also discusses it: http://en.wikipedia.org/wiki/Ternary_operation