Table of Contents
Previous Section Next Section

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.


Table of Contents
Previous Section Next Section