29.3 The ?: Construct

I l @ ve RuBoard

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


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net