Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
52
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 15: C You Again 197

Breaking out of a loop

Loops aren’t infinite if you have a way to break out of them. For most loops, that escape clause is provided in the looping statement itself. In the for state­ ment, the escape condition is the middle item, as in

for(a=32;a<128;a=a+1)

The escape clause is a<128, which is the condition on which the loop ends.

Some loops, however, are designed without an end. That’s because the condi­ tion that ends the loop happens elsewhere. In that case, the loop is designed to be eternal — which is fine, as long as some condition elsewhere eventually breaks the loop.

As an example, most word processors work with an infinite loop hidden inside their programs. The loop sits and scans the keyboard, over and over, waiting for you to type a command. Only when you type the proper “I want to quit” command does the thing stop and you return to DOS. It’s like a controlled infi­ nite loop — it’s not really infinite because you have a way out.

The following program is TYPER1.C, a first stab at a word processor, though you can do nothing in the program except type and see what you type on the screen. The program is set up with an on-purpose infinite for loop. The break keyword is then used with the if command to bust out of the loop when you press the ~ (tilde) key:

#include <stdio.h>

int main()

{

char ch;

puts(“Start typing”);

puts(“Press ~ then Enter to stop”);

for(;;)

{

ch=getchar();

if(ch==’~’)

{

break;

}

}

printf(“Thanks!\n”);

return(0);

}

198 Part III: Giving Your Programs the Ability to Run Amok

This program wins the award for having the most indentation and curly braces to this point in this book. Be careful as you type it into your editor. Save the file to disk as TYPER1.C.

Compile TYPER1.C.

Run the resulting program, which works somewhat like a typewriter. You can type away and fill the screen with text.

When you’re done typing, press the tilde (~) key and then Enter. (This is

TYPER’s only “command.”) You’re done.

The for(;;) statement doesn’t error. The reason is that the semicolons are required, but what’s between them isn’t (a peculiarity of the for keyword).

I read the for(;;) command aloud as “for ever.”

The for loop in TYPER1.C is infinite because its “while true” condition is missing. Gone! The compiler therefore assumes that the condition is true all the time and that the program loops infinitely.

The first and last parts of the for statement’s items aren’t included either, though the semicolons inside the parentheses are still required in order to meet the demands of C etiquette.

Because several statements belong to the for loop, they’re enclosed in curly braces.

The getchar function waits for a key to be pressed on the keyboard and displays that character. The character is then saved in the ch variable.

The if statement tests the ch variable to see whether it’s equal to the

~ (tilde) character. Note that two equal signs are used. If the comparison is true, indicating that the user pressed the ~ key, the break command is executed. Otherwise, break is skipped and the loop is repeated, reading another character from the keyboard.

The break keyword

The break keyword gets you out of a loop — any loop in C, not just a for loop. No matter what the loop’s ending condition is, break immediately issues a “parachute out of this plane” command. The program continues with the next statement after the loop:

break;

Chapter 15: C You Again 199

The break keyword is a C language statement unto itself and must end prop­ erly with a semicolon.

The loop that break breaks you out of doesn’t have to be an endless loop. break can stop any loop, at any time. It’s often used with an if statement to test some condition. Based on the results of the test, the loop is stopped by using break (just as was done with TYPER1.C in the preceding section).

break stops only the loop it’s in. It doesn’t break out of a nested loop, or a loop within a loop. See Chapter 18 for more information on nested loops.

If you use break outside of a loop — when there’s nothing to break out of — the compiler goes berserk and generates an error.

It’s funny how the word is break and not brake. The same twisted logic applies to the Break key on your keyboard.

200 Part III: Giving Your Programs the Ability to Run Amok