How to Go Back in C Using Goto

In C language, it is usually not possible to directly return to the previous step of execution. However, you can use labels and the goto statement to jump to a specific location in the program, achieving a functionality similar to returning to the previous step of execution.

Here is a simple example code:

#include <stdio.h>

int main() {
    int choice;
    
start:
    printf("1. Option 1\n");
    printf("2. Option 2\n");
    printf("3. Exit\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);
    
    switch(choice) {
        case 1:
            printf("You chose Option 1\n");
            break;
        case 2:
            printf("You chose Option 2\n");
            break;
        case 3:
            printf("Exiting program\n");
            return 0;
        default:
            printf("Invalid choice, please try again\n");
            goto start;
    }
    
    goto start;
    
    return 0;
}

In the code above, a start tag and goto statement are used to allow the program to return to a specified position during execution. When the user inputs an invalid option, the program will jump back to the start tag and display the options again for the user to choose from.

It should be noted that using the goto statement will increase code complexity and difficulty of maintenance, so it is advisable to avoid using the goto statement as much as possible in actual development. A better practice is to achieve program control flow jumps through function calls and state preservation.

bannerAds