C Programming Tutorial
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:
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.
Let's see a simple example to use goto statement in C language.
#include <stdio.h>
int main() {
int age;
ineligible:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n");
scanf("%d", &age);
if(age<18)
goto ineligible;
else
printf("You are eligible to vote!\n");
return 0;
}
Output:
You are not eligible to vote!
Enter you age:
11
You are not eligible to vote!
Enter you age:
44
You are eligible to vote!