C – goto statement with example


C – goto statement with example


The goto statement is rarely used because it makes program confusing, less readable and complex. Also, when this is used, the control of the program won’t be easy to trace, hence it makes testing and debugging difficult.

C – goto statement

When a goto statement is encountered in a C program, the control jumps directly to the label mentioned in the goto stateemnt
Syntax of goto statement in C
goto label_name;
..
..
label_name
: C-statements

Flow Diagram of goto

Example of goto statement

#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++){
sum
= sum+i;
if(i==5){
goto addition;
}
}

addition
:
printf
("%d", sum);

return 0;
}
Output:
15
Explanation: In this example, we have a label addition and when the value of i (inside loop) is equal to 5 then we are jumping to this label using goto. This is reason the sum is displaying the sum of numbers till 5 even though the loop is set to run from 0 to 10.

Post a Comment

Previous Post Next Post