Advanced Program Control 333
13
Summary ............................................................................................................
Today’s lesson covers a variety of topics related to program control. You learned about
thegotostatement and why you should avoid using it in your programs. You saw that the
breakandcontinuestatements give additional control over the execution of loops and
that these statements can be used in conjunction with infinite loops to perform useful
programming tasks. You also learned how to use the exit()function to control program
termination. Finally, you saw how to use the system()function to execute system com-
mands from within your program.
Q&A ....................................................................................................................
Q Is it better to use a switchstatement or a nested loop?
AIf you’re checking a variable that can take on more than two values, the switch
statement is almost always better. The resulting code is easier to read, too. If you’re
checking a true/false condition, go with an ifstatement.
Q Why should I avoid a gotostatement?
AWhen you first see a gotostatement, it’s easy to believe that it could be useful.
However,gotocan cause you more problems than it fixes. A gotostatement is an
unstructured command that takes you to another point in a program. Many debug-
gers(software that helps you trace program problems) can’t interrogate a goto
properly. gotostatements also lead to spaghetticode—code that goes all over the
place.
#include <iostream.h>
#include <stdlib.h>
int main()
{
system(“PAUSE”);
return 0;
}
Thesystem(“PAUSE”)causes the system to pause until a key is pressed. This
allows you to view the output from the listing; otherwise, the window that
displays the output is closed before you have a chance to see it.
21 448201x-CH13 8/13/02 11:12 AM Page 333