Break and Continue

December 21, 2007

Break and continue keywords help control the flow of execution. They could be used everywhere in the code. However, they are commonly used in loops and switch statements because that is where they are most needed.

Similarity and Difference

Basically both break and continue are very much similar. They both tell the compiler to skip the rest of the code. How much code is skipped depends on where it is used. When used within a switch statement or the three loops, only code within the structure is affected. Otherwise, the whole method will be affected.

The difference appears when used within a loop. In a loop, continue will skip the rest of the loop and continue running the next loop. If break is used instead, the whole loop will be abandoned. Execution will continue after the loop.

Switch statement

Break is commonly seen in switch statement. The switch statement in X++ is similar to those of C language. Execution begins at the case node that fulfils the criteria until the end of the switch structure. A break keyword is used to stop executing the rest of the structure.

The objective here is to stop executing the rest of the code within the switch statement. Base on the behavior of two statements discussed above, using continue here will just produce the same result.

While Loop, Do While Loop and For Loop

This is where a choice between the two statements will make a different. The following code segment demonstrates the effect of keywords break and continue in a loop.

The code segment prints the even number within 1 to 10. The do while loop here is an infinite loop. The keyword break is used to end the loop when exit condition is fulfilled. The keyword continue is used to decide whether to execute the rest of the loop which in turn prints the number.

int nCtr;
;
// print even number from 1 to 10.
do {
    nCtr ++;

    // ends loop if exceeded 10.
    if (nCtr > 10) {
        break;
    }

    // do not print the number if not even.
    if (nCtr mod 2) {
        continue;
    }

    print nCtr;
} while(1);

Method Exit Point

There is a common practice to exit a method in the middle for methods that returns a value. This is less seen in void methods. The keywords break and continue could be used to achieve this for void methods.

1 comment :

faizull said... (December 19, 2011 at 4:36 AM)

Good..Really helpful..