Micron Document
The C Programming Language, Ansi C


← Prev · 70/277 · Next →

As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.

Exercise 3-2. Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like n and t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters.

We have already encountered the

while

and

for

loops. In

while (

expression

)

statement

the

expression

is evaluated. If it is non-zero,

statement

is executed and

expression

is re-evaluated. This cycle continues
until

expression

becomes zero, at which point execution resumes
after

statement

.

The for statement

for (

expr

1

;

expr

2

;

expr

3

)

statement

is equivalent to

expr

1

;
while (

expr

2

) {

statement

expr

3

;
}

except for the behaviour of

continue

, which is described in

Section 3.7

.

Grammatically, the three components of a for loop are expressions. Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a relational expression. Any of the three parts can be omitted, although the semicolons must remain. If expr1 or expr3 is omitted, it is simply dropped from the expansion. If the test, expr2, is not present, it is taken as permanently true, so

for (;;) {
...
}

is an infinite'' loop, presumably to be broken by other means, such as a

break

or

return

.

Whether to use while or for is largely a matter of personal preference. For example, in

while ((c = getchar()) == ' ' || c == 'n' || c = 't')
; /* skip white space characters */

there is no initialization or re-initialization, so the

while

is most
natural.