If you learned to program in a language without ``break'' and
``continue'' statements, such as Pascal, then you've probably gotten
into the habit of writing ugly loops.
For example, take a look at ``examples/break1.c'' (or view
it directly). It reads numbers from
the keyboard until a non-positive number is entered, at which point it
returns the total of the positive numbers entered. Notice how the
programmer has chosen to use a variable ``finished'' to keep track of
whether a negative number has been entered yet.
Now take a look at ``break2.c'' (or view it directly), which does the same thing in a different
way. Here we have done away with the ``finished'' variable. Instead,
when we finally read a negative number we simply break out of the loop
and go on our way. Compare the two programs, and run them to convince
yourself that they really do the same thing. (Incidentally, notice
that we've written a loop that would run forever if it weren't for the
break!)
As you write larger programs, you will find similar opportunities to
use ``continue'' to simplify your programs. There is a good simple
example in the text.
Hamlet Project
hamlet@cs.utah.edu