Else Clause; Conditional Expressions In C
We just used an
else
after an if
. The most general form of if
isif (expression) statement1 else statement2the
else
part is optional, but often useful. The canonical example sets x
to the minimum of a
and b
:if (a < b) x = a; else x = b;Observe that there's a semicolon after
x=a
.C provides an alternate form of conditional which is often more concise. It is called the ``conditional expression'' because it is a conditional which actually has a value and can be used anywhere an expression can. The value ofa<b ? a : b;is
a
if a
is less than b
; it is b
otherwise. In general, the formexpr1 ? expr2 : expr3means ``evaluate
expr1
. If it is not zero, the value of the whole thing is expr2
; otherwise the value is expr3
.''To set x
to the minimum of a
and b
, then:x = (a<b ? a : b);The parentheses aren't necessary because `?:' is evaluated before `=', but safety first.Going a step further, we could write the loop in the lower-case program as
while( (c=getchar( )) != '\0' ) putchar( ('A'<=c && c<='Z') ? c-'A'+'a' : c );If's and else's can be used to construct logic that branches one of several ways and then rejoins, a common programming structure, in this way:
if(...) {...} else if(...) {...} else if(...) {...} else {...}The conditions are tested in order, and exactly one block is executed; either the first one whose if is satisfied, or the one for the last
else
. When this block is finished, the next statement executed is the one after the last else. If no action is to be taken for the ``default'' case, omit the last else
.For example, to count letters, digits and others in a file, we could writemain( ) { int let, dig, other, c; let = dig = other = 0; while( (c=getchar( )) != '\0' ) if( ('A'<=c && c<='Z') || ('a'<=c && c<='z') ) ++let; else if( '0'<=c && c<='9' ) ++dig; else ++other; printf("%d letters, %d digits, %d others\n", let, dig, other); }The `++' operator means ``increment by 1''; we will get to it in the next section.
0 comments:
Post a Comment