• Home
  • Break, Continue and Goto Statements in C language

Break, Continue and Goto Statements in C language

The break, continue, and goto statements are control flow statements in the C programming language that allow you to alter the normal flow of a program.

The break statement is used to exit a loop or switch statement prematurely. When a break statement is encountered inside a loop or switch statement, control is immediately transferred to the statement following the loop or switch. The syntax for a break statement is as follows:

break;

For example, consider the following code:

int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d ", i);
}
printf("\n");

In this example, the loop iterates 10 times, from 0 to 9. However, when the value of i becomes 5, the break statement is encountered and the loop is exited. The output of this code is “0 1 2 3 4”, as the loop terminates before the value of i becomes 6.

The continue statement is used to skip the remainder of the current iteration of a loop and continue with the next iteration. When a continue statement is encountered inside a loop, control is immediately transferred to the loop’s increment/decrement expression. The syntax for a continue statement is as follows:

continue;

For example, consider the following code:

int i;
for (i = 0; i < 10; i++) {
if (i % 2 == 1) {
continue;
}
printf("%d ", i);
}
printf("\n");

In this example, the loop iterates 10 times, from 0 to 9. However, when the value of i is odd (i % 2 == 1), the continue statement is encountered and the remainder of the current iteration is skipped. The output of this code is “0 2 4 6 8”, as the loop skips the iterations where the value of i is odd.

The goto statement is used to transfer control to a labeled statement in the same function. The syntax for a goto statement is as follows:

goto label;

...
label:
// code to execute

For example, consider the following code:

int i;
for (i = 0; i < 10; i++) {
if (i == 5) {
goto end;
}
printf("%d ", i);
}
end:
printf("\n");

In this example, the loop iterates 10 times, from 0 to 9. However, when the value of i becomes 5, the goto statement is encountered and control is transferred to the labeled statement “end”. The output of this code is “0 1 2 3 4”, as the loop terminates before the value of i becomes 6.

It is important to use these control flow statements sparingly, as they can make your code harder to read and understand. They should only be used when necessary to improve the clarity or efficiency of your code.