maandag 18 juni 2007

The BREAK and CONTINUE Statements

The break and continue statements enable a program to skip over parts of the code. You can use the break statement in a switch statement and in any of the loops. It causes the program excecution to pass the next statement following the switch or loop. The continue statement is used in loops and causes a program to skip the rest of the body of the loop and then start a new loop cycle.

example:

while (cin.get(ch))
{
statement1
if (ch == '\n')
continue;
statement2
}
statement3

continue skips rest of loop body and starts a new cycle

while (cin.get(ch))
{
statement1
if (ch == '\n')
break;
statement2
}
statement3
break skips rest of loop and goes to following statement, in this case statement3

NOTE:
continue NOT skips the UPDATE EXPRESSION, it skips however the loop's body. We are talking about a FOR loop NOW.
But in a WHILE loop, if the update expression comes after the continue, it will be skipped, somethimes that gives trouble!

Geen opmerkingen: