1 <!DOCTYPE HTML PUBLIC
"-//W3O//DTD W3 HTML 2.0//EN">
2 <!-- This collection of hypertext pages is Copyright 1995-7 by Steve Summit. -->
3 <!-- This material may be freely redistributed and used -->
4 <!-- but may not be republished or sold without permission. -->
7 <link rev=
"owner" href=
"mailto:scs@eskimo.com">
8 <link rev=
"made" href=
"mailto:scs@eskimo.com">
9 <title>18.2.5: The Conditional Operator
</title>
10 <link href=
"sx4db.html" rev=precedes
>
11 <link href=
"sx4c.html" rel=precedes
>
12 <link href=
"sx4b.html" rev=subdocument
>
15 <H3>18.2.5: The Conditional Operator
</H3>
17 <p>[This section corresponds to K
&R Sec.
2.11]
18 </p><p>C has one last operator which we haven't seen yet.
20 conditional or ``ternary'' or
<TT>?:
</TT> operator,
21 and in action it looks something like this:
23 average = (n
> 0) ? sum / n :
0
25 </p><p>The syntax of the conditional operator is
27 <I>e1
</I> ?
<I>e2
</I> :
<I>e3
</I>
29 and what happens is that
<I>e1
</I> is evaluated,
30 and if it's true then
<I>e2
</I> is evaluated
31 and becomes the result of the expression,
33 <I>e3
</I> is evaluated and becomes the result of the expression.
35 the conditional expression is
36 sort of an
<TT>if
</TT>/
<TT>else
</TT> statement
37 buried inside of an expression.
38 The above computation of
<TT>average
</TT> could be written out
39 in a longer form using an
<TT>if
</TT> statement:
45 </p><p>The conditional operator,
48 and can therefore be used wherever an expression can be used.
49 This makes it more convenient to use
50 when an
<TT>if
</TT> statement
51 would otherwise cause other
53 of code to be needlessly repeated.
55 suppose we were trying to write a complicated function call
57 func(a, b +
1, c + d,
<I>xx
</I>, (g + h + i) /
2);
59 where
<I>xx
</I> was supposed to be
<TT>f
</TT> if
<TT>e
</TT> was true
61 Using an
<TT>if
</TT> statement, we'd have to write:
64 func(a, b +
1, c + d, f, (g + h + i) /
2);
65 else func(a, b +
1, c + d,
0, (g + h + i) /
2);
67 We could write this more compactly, more readably, and more safely
68 (it's easier both to see and to guarantee
69 that the other arguments are always the same)
72 func(a, b +
1, c + d, e ? f :
0, (g + h + i) /
2);
74 </p><p>(The obscure name ``ternary,'' by the way,
75 comes from the fact that the conditional operator
76 is neither unary nor binary;
77 it takes
<em>three
</em> operands.)
81 <a href=
"sx4db.html" rev=precedes
>prev
</a>
82 <a href=
"sx4c.html" rel=precedes
>next
</a>
83 <a href=
"sx4b.html" rev=subdocument
>up
</a>
84 <a href=
"top.html">top
</a>
87 This page by
<a href=
"http://www.eskimo.com/~scs/">Steve Summit
</a>
88 //
<a href=
"copyright.html">Copyright
</a> 1996-
1999
89 //
<a href=
"mailto:scs@eskimo.com">mail feedback
</a>