break
Exits The Loop
Are you done with the read_int
exercise? I imagine you could've written something like this:
while (isdigit(c = getchar())) {
result = result * 10 + (c - '0');
}
and if so, great job! You could have written a longer version too, and it's completely fine. Something like this will work:
finished = 0;
while (!finished) {
c = getchar();
if (c >= '0' && c <= '9') { /* same as isdigit(c) */
result = result * 10 + (c - '0');
} else {
finished = 1;
}
}
This is the second time we write a while
loop this way:
while (!finished) {
...
}
The finished
variable gets eventually assigned to 1 inside the loop, and the loop ends after that.
There is an easier way to do the same thing: the break
instruction. break;
means "exit the loop right now". Here I'll use while (1)
, which is an infinite loop – or, better to say, it would've been an infinite loop if I hadn't used break
inside:
while (1) {
c = getchar();
if (c >= '0' && c <= '9') { /* same as isdigit(c) */
result = result * 10 + (c - '0');
} else {
break;
}
}
Since break
exits the loop, it sometimes makes sense to check the exit condition first:
while (1) {
c = getchar();
if (!isdigit(c)) {
break;
}
result = result * 10 + (c - '0');
}
But break
is useful not only for would-be-infinite loops, but for regular loops as well. Let's look at the example on the next page!