Break, Continue and GOTO statement

Break statement in C++

Statement in C++ : The break statement, which was already covered in the switch..case, can also be used in the loops. When a loop statement is encountered in the loops the control is transferred to the statement outside the loop. When there are nested loops it breaks only from the current loop in which it was written.

The continue statement in C++

The continue statement in C++ causes the next iteration of the enclosing loop to begin. When this is encountered in the loop, the rest of the statements in the loop are skipped and control passes to the condition. For e.g., consider the C++ program that prints the sum of only positive numbers:

int num, total = 0;
// enter the number and store it in num.
do
{
if(num == 0)
Break;
if(num < 0)
continue; // If this is encountered, next statement is skipped total+=num;
}
while (1);
}

GOTO statement in C++

The GOTO statement in C++ can be used to branch to another statement of the program. This is rarely used as it violates the principle of structured programming. However we can use it when we want to exit from deeply nested loops. The general format is
goto label;
where label is a name (tag) followed by colon. For e.g.,
for(..)
{
for(..)
{
for(..)
{
for(..)
{
if (condition)
goto cleanup;
}
}
}
}
Cleanup: statements;
:

A good programmer will use control statements effectively in order to avoid the usages of unconditional branching statement –goto.

Leave a Reply

Your email address will not be published.