C goto Statement

The goto statement is used to alter the normal sequence of a C program. 

Syntax of goto statement

goto label;
... .. ...
... .. ...
... .. ...
label: 
statement;
The label is an identifier. When goto statement is encountered, control of the program jumps to label: and starts executing the code.
How goto statement works?

Example: goto Statement


// Program to calculate the sum and average of maximum of 5 numbers
// If user enters negative number, the sum and average of previously entered positive number is displayed

# include <stdio.h>

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 user enters negative number, flow of program moves to label jump
        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

Reasons to avoid goto statement

The use of goto statement may lead to code that is buggy and hard to follow. For example:
one: 
for (i = 0; i < number; ++i)
{
    test += i;
    goto two;
}
two: 
if (test > 5) {
  goto three;
}
... .. ...
Also, goto statement allows you to do bad stuff such as jump out of scope.
That being said, goto statement can be useful sometimes. For example: to break from nested loops.

Should I or shouldn't I use goto statement?

If you think the use of goto statement simplifies your program. By all means use it. The goal here is to create code that your fellow programmers can understand easily.

No comments:

Post a Comment