The ? Operator

The ? operator is a ternary operator (it works on three expressions). It has this general form:

expression1 ? expression2 : expression3;

If expression1 is true, then the outcome of the operation is expression2; otherwise, it is the value of expression3.

Programming Tip 

The ? is often used to replace if-else statements of this general type:

 if(expression1)  var = expression2; else var = expression3; 

For example, the sequence

if(y < 10) x = 20; else x = 40; 

can be rewritten like this:

x = (y<10) ? 20 : 40;

Here, x is assigned the value of 20 if y is less than 10 and 40 if it is not.

One reason that the ? operator exists, beyond saving typing on your part, is that the compiler can produce very fast code for this statement—much faster than for the similar if-else statements.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: