Ternary Operator

<condition> ? <true-case-code> : <false-case-code>;
The ternary operator allows you to execute different code depending on the value of a condition, and the result of the expression is the result of the executed code. For example:
int five_divided_by_x = ( x != 0 ? 5 / x : 0 );

Here, x != 0 is checked first, and if it is true, then the division, 5/x, takes place. Otherwise, the value is 0. The ternary operator is excellent for situations where you need to choose two different values depending on a single condition, but it is not a good general-purpose substitute for if/else statements.

The ternary operator is particularly useful when initializing const fields of a class as those fields must be initialized inside the initialization list, where if/else statements cannot be used (read more about initialization lists in C++). For example:

class IntPtr
    IntPtr (const int *p_other)
        : _p_other( p_other != 0 : new int( * p_other ) : 0 )
    const int * const _p_other;

In the above code, without using the ternary operator, it would not be possible to initialize the _p_other value since it is a const pointer.