18.2.5: The Conditional Operator

[This section corresponds to K&R Sec. 2.11]

C has one last operator which we haven't seen yet. It's called the conditional or ``ternary'' or ?: operator, and in action it looks something like this:

	average = (n > 0) ? sum / n : 0

The syntax of the conditional operator is

	e1 ? e2 : e3
and what happens is that e1 is evaluated, and if it's true then e2 is evaluated and becomes the result of the expression, otherwise e3 is evaluated and becomes the result of the expression. In other words, the conditional expression is sort of an if/else statement buried inside of an expression. The above computation of average could be written out in a longer form using an if statement:
	if(n > 0)
		average = sum / n;
	else	average = 0;

The conditional operator, however, forms an expression and can therefore be used wherever an expression can be used. This makes it more convenient to use when an if statement would otherwise cause other sections of code to be needlessly repeated. For example, suppose we were trying to write a complicated function call

	func(a, b + 1, c + d, xx, (g + h + i) / 2);
where xx was supposed to be f if e was true and 0 if it was not. Using an if statement, we'd have to write:
		func(a, b + 1, c + d, f, (g + h + i) / 2);
	else	func(a, b + 1, c + d, 0, (g + h + i) / 2);
We could write this more compactly, more readably, and more safely (it's easier both to see and to guarantee that the other arguments are always the same) by writing
	func(a, b + 1, c + d, e ? f : 0, (g + h + i) / 2);

(The obscure name ``ternary,'' by the way, comes from the fact that the conditional operator is neither unary nor binary; it takes three operands.)

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1996-1999 // mail feedback