devxlogo

Why Not to Use an Exit Within a Loop

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.

See also  Is Machine Learning Automating Creativity in Graphic Design?

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist