I l@ve RuBoard Previous Section Next Section

29.3 The ?: Construct

The ? and : operators work much the same as if/then/else. Unlike if/then/else, the ?: operators can be used inside of an expression. The general form of ?: is:

(expression) ? expr1 : expr2; 

For example, the following assigns to amount_owed the value of the balance or zero, depending on the amount of the balance:

amount_owed = (balance < 0) ? 0 : balance; 

The following macro returns the minimum of its two arguments:

#define min(x, y) ((x) < (y) ? (x) : (y))

The C++ library has a perfectly good min function so you don't have to define it yourself. Use the template for safety and efficiency.

    I l@ve RuBoard Previous Section Next Section