
In this chapter you will learn how to create goto statement in C programs. Also learn when to use the goto statemnt and when not to.
C Programming goto Statement
Goto statement in C program is known as jump statement.
The goto statement is used to change the general flow of a C program.
C goto syntax
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
Here label is the identifier. When the program goto statement is encountered, program control label: jumps to it and execution of the label block degins.
Example: goto statement
// Find the sum and average of maximum 5 numbers.
// If the user inputs a negative number, the sum and average of the previous numbers will be displayed.
# include
int main()
{
const int maxInput = 5;
int i;
double number, average, sum=0.0;
for(i=1; i<=maxInput; ++i)
{
printf("%d. Enter a number: ", i);
scanf("%lf",&number);
//If the user enters a negative number, the control of the program will go to the jump label.
if(number < 0.0){
goto jump;
}
sum += number; // sum = sum+number;
}
jump:
average=sum/(i-1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}
output
1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53
Reasons not to use the goto statement
The use of goto makes the program difficult and something the program may appear to have bugs. For example:
one:
for (i = 0; i < number; ++i)
{
test += i;
goto two;
}
two:
if (test > 5) {
goto three;
}
... .. ...
However, the goto statement can sometimes be useful. For example, if you want to take a break from a nested loop.
Should/shouldn't use goto statement?
If you feel that using goto statement will make your program easier then you can use it. Because the purpose here is to simplify the code so that your followers can understand your code very easily.