Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jan 4, 2006

Why Not to Use an Exit Within a Loop

This recent tip gives advice on how to include an exit within a loop to avoid repeated code. While avoiding repeated code is prudent, using an exit from a loop is not. Using the exit can result in ill-defined variable status.

One of the first things students are told about creating "well-structured code" is not to use an exit or break to jump out of a loop. This is equivalent to using a GOTO statement and leads to code with unplanned side effects.

You can avoid both duplicated lines of code and the use of exit by using the apropriate loop control, as illustrated in the following code:


int main()
{
    command instructions;
    int counter = 0;

    cout < endl < "Enter Command > ";
    instructions = get_command();

    while(instructions != quit)
    {
        counter += 1;
        cout < endl < "Enter Command > ";
        instructions = get_command();
    }
    cout < endl < "entered " < counter + 1 < " commands" < endl;
    return 0;
}
The problem is that the lines:

    cout < endl < "Enter Command > ";
    instructions = get_command();
occurr before and within the loop. This is a valid concern. However, this pattern should be taken as a very strong indication that a do .. while( ) loop and not a while () { }; is needed.

The original tip gave the following code:


int main()
{
    command instructions;
    int counter = 0;

     while(1)
     {
         cout < endl < "Enter Command > ";
         instructions = get_command();                 
         if(instructions == quit)
             break;
         counter += 1;
     }
     cout < endl < "entered " < counter + 1 < " commands" < endl;
}
This should be changed as shown below:

int main(void)
{
    command instructions;
    int counter = 0;

     do
     {
         cout < endl < "Enter Command > ";
         instructions = get_command();                 
         if(instructions == quit)
             break;
         counter += 1;
     }while (command != quit);
     counter -= 1;
     cout < endl < "entered " < counter + 1 < " commands" < endl;
}
Note also that the correct definition of main uses void in the argument list. This makes the code portable.

David Pycock
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date