The ‘goto’ in C Programming

C Programming @ Freshers.in

In C programming, the ‘goto’ keyword is a controversial and powerful tool for altering the flow of code execution. This article provides a comprehensive explanation of the ‘goto’ keyword, its role in code control, and includes real-world examples with outputs to illustrate its use cases and potential implications.

Understanding the ‘goto’ Keyword

The ‘goto’ keyword in C allows programmers to transfer control to a labeled statement within the same function. While ‘goto’ can be used to create efficient and structured code, it can also lead to spaghetti code if misused. It’s essential to use ‘goto’ judiciously and only when alternative control structures are impractical.

Syntax for ‘goto’ Statement:

goto label;

Syntax for Label Declaration:

label:

Example 1: Using ‘goto’ for Error Handling

#include <stdio.h>
int main() {
    int num;
    printf("Enter a positive number: ");
    scanf("%d", &num);
    if (num <= 0) {
        printf("Error: Invalid input\n");
        goto end; // Jump to the 'end' label
    }
    printf("You entered a positive number: %d\n", num);
    end:
    printf("End of program\n");
    return 0;
}

Output (Invalid Input):

Enter a positive number: -5
Error: Invalid input
End of program

Output (Valid Input):

Enter a positive number: 10
You entered a positive number: 10
End of program

In this example, ‘goto’ is used for error handling. If the user enters a non-positive number, the program prints an error message and jumps to the ‘end’ label to exit gracefully.

Use Cases for ‘goto’

  1. Error Handling: ‘goto’ can be useful for handling error conditions and avoiding nested if-else blocks.
  2. Exiting Loops: ‘goto’ can be employed to exit nested loops when specific conditions are met.

Example 2: Using ‘goto’ to Exit a Loop

#include <stdio.h>
int main() {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= 5; j++) {
            if (i * j > 10) {
                goto exit_loop;
            }
            printf("%d * %d = %d\n", i, j, i * j);
        }
    }
    exit_loop:
    printf("Exiting the nested loop\n");
    return 0;
}

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
Exiting the nested loop

In this example, ‘goto’ is used to exit the nested loops when the product of ‘i’ and ‘j’ exceeds 10.

Author: user