A Loop with an Exit Condition

A Loop with an Exit Condition

Here is a pattern you will see quite often when structuring your code in loop constructs:

01    enum command {  start, stop, wait, quit };02    command instructions;03    int counter = 0;0405    cout  ";06    instructions = get_command();0708    while(instructions != quit)09    {10        counter += 1;11        cout  ";12        instructions = get_command();13    }

Notice that lines 5 and 6 are identical to lines 11 and 12.

During code modifications, it is not always clear that these two sets of lines need to be maintained in parallel. You might change line 5 but not realize that line 11 must also be modified to stay in sync with line 5. There is a better way to structure the code that removes redundancies:

01    command instructions;02    int counter = 0;0304    while(1)05    {06        cout  ";07        instructions = get_command();08        if(instructions == quit)09            break;10        counter += 1;11   }

Notice the redundant lines are no longer present. The code created an infinite loop and, in the middle of the loop, tests the exit condition to break out of the loop. The exit condition is the reverse of the condition coded in the original loop. Instead of instructions != quit it is coded as instructions == quit. The repeating code now goes above the exit condition and all other code from the original loop goes below the condition.

Here is the complete source code for the original and modified versions of the loop:

//*******************************************************************#include#include using namespace std;enum command {  start, stop, wait, quit };command get_command(){    int x = getch();    command cmd = command(x - '0');    switch(cmd)    {        case start:            cout  ";    instructions = get_command();    while(instructions != quit)    {        counter += 1;        cout  ";        instructions = get_command();    }    cout  ";         instructions = get_command();                          if(instructions == quit)             break;         counter += 1;     }     cout 


Share the Post: