Break, Continue and Goto in C Programming

C is the language which executes the statements within it sequentially – one after the other. Even if it has conditional statements or loop statements, the flow of the program is from top to bottom. There is no random jumping or skipping of sequential flow. But our program is to address any real world requirement and it can never be very straight forward to execute one after the other. In some cases, we have to deviate from normal sequential flow of the code and have to jump to execute next set of statements. This can be done by using break, continue and goto statements.

Break

Break statement is used to discontinue the normal execution of the code without any condition and it will jumps out from the current executing loop. We can have conditions to check if we have to break or not, but those conditions are not part of break statement. Instead we may have if statement for the same.

For example when we execute the loops, when we encounter some values, we might have to skip the execution of the statements. But we cannot exclude the numbers in for loop or by any conditions. Suppose we are displaying the first 15 natural numbers using while loop. Let us have bit different code than above to illustrate break statement.

#include <stdio.h> 

void main() {
	int intNum = 1;

	printf("\n Example of BREAK Statement using WHILE Loop\n");
	printf("First 15 natural numbers are: \n");
	while (1){
		printf("%d  ", intNum++);
		if (intNum == 16)
			break;
	}
	printf("\n Outside the while loop and value of intNum is %d", intNum);
}

Here while(1) will always evaluate it as TRUE and there is no other conditional checks on the variables or any other factors. Hence it will be an infinite loop which will print the numbers from 1 to infinite. In order to stop the loop after printing 15, we have to break the loop. This is done by using break statement. But in order to execute break, we need to check if it has printed 15th number or not. Hence we have used if statement to check the value of intNum. Now when it reaches break, it will immediately come out of the loop irrespective of loops return value – whether TRUE or FALSE. We can see this in the result above. It did not print the numbers once it reaches 16.

The same method can be used to break from for or do/while loops. It works in the same way there also. It immediately stops from the current execution of the loop and jumps from it.

#include <stdio.h> 
void main() {
	int intNum = 1;

	printf("\n Example of BREAK Statement using FOR Loop\n");
	 
	for (intNum = 1; intNum > 0; intNum++){
		printf("This is a C program!");
		printf("\n This program illustrates the usage of BREAK statement");
		break;
		printf("\n We have reached after the break statement within the loop"); // this statement will never be displayed until break is present above
	}
	printf("\n Break statement within the loop has been executed and is outside the loop now");
}

This break statement is also used with switch statements. Since switch statement will not break from its execution after executing its matching case statement, we have to explicitly make it to break. This is done by using the break statement. This is explained the switch/case topic below.

Continue

this is similar to break statement, but it will not jump out of the loop instead stop executing the set instructions inside loop body for current iteration and jumps to execute the body of loop for next iterations.

Consider a simple code with for loop, which displays some simple messages 4 times. Let us add a condition that when the iteration is 3, do not print last message. This is done by using if conditions followed by ‘continue’ statement. We can notice here that, it has skipped the last message and continued with next iteration.

#include <stdio.h>

void main() {
    int intNum = 1;

    printf("\nExample of CONTINUE Statement using FOR Loop\n");
     
    for (intNum = 1; intNum<5 ; intNum++){
        printf("\n\nThis is %d iteration", intNum);
        printf("\nThis program illustrates the usage of CONTINUE statement");
        if (intNum == 3)
            continue;
        printf("\nWe have reached after the break statement within the loop"); // this statement will not be displayed for 3rd iteration
    }
    printf("\nOutside the loop");
}

Continue statement can be used in for loops, while and do/while loops for breaking the current execution and to continue with next set of iterations.

Goto

This statement is a unconditional jump statement. It can be used anywhere in the program to jump from its current execution to some other lines in the code. Once it is jumped to some other line, it will continue executing the codes from there sequentially. It cannot come back again to previous execution lines. In order to refer to the line it has to jump, we label the line. General syntax for goto statement is :

goto label_name;
goto error_not_Valid_Number;
goto error_division_by_zero;
goto display_name;

The jumping label can be anywhere in the code. Either before goto statement or after the goto statement. It does not matter where the label exists.

This kind of jump is anything and is unconditional. Usually we use goto statement to handle errors. But this will reduce the readability of the code and create confusion to the one looking at the code. Hence it always advisable to reduce the use of goto statements in the code.

Let us consider the example below to divide two numbers. It will look little complex, but try executing it with different values and changing the label positions. Here the program checks for the two numbers if it is zero. If the first number is zero, then flow of the program jumps to the label error_num1_zero. It will then print the warning message and continue with rest of the code. It will not come back to execute other statements that it has left. In our case below, num1 is non-zero. Hence it checks second number. It is zero. Hence it jumps to error_num2_zero. It prints the error message there and continues with the rest of the statements irrespective of the labels. Hence we can see warning message is also displayed in the result, which is irrelevant to us as first number is non-zero. Here we cannot use break statement as it is allowed only inside loops and switch statements. Hence we need to have some other mechanism to break from this execution. We can use another label to jump to end of the code. i.e.;

goto end; // jumps to the label end

We have commented it in below program. Uncomment above statement and label in the to see the result.  Suppose both the numbers are non-zero. Then it will divide the numbers as usual. But it will continue executing the error messages even if it has label. Since C executes sequentially and is not bothered about labels for normal execution, it will display the error messages in labels too. If we have to avoid them being displayed, then we have to explicitly make the control of the code to jump to label end. Uncomment these goto end and end labels and execute the program to see the results.

#include <stdio.h> 

void main() {
	int intNum1 = 100, intNum2 = 0;
	if (intNum1 == 0)
		goto error_num1_zero;// jumps to the label error_num1_zero
	
	if (intNum2 == 0)
		goto error_num2_zero;// jumps to the label error_num2_zero

	// below two lines will be executed if both the numbers are non-zero, else it will continue executing any one of the label
	int result = intNum1 / intNum2;
	printf("Result is %d", result);
	//goto end;
	error_num2_zero:printf("\nResults in Division by zero!"); // prints the error message and continues with rest of the statements
	//goto end;
error_num1_zero: printf("\nFirst number is zero and hence result will be zero");// prints the error message and continues with rest of the statements

//end: 
	printf("\nEnd of the program!");
}

Translate »