Goto Statement in C

By | February 20, 2023

Prerequisite – Control Statements in C
The goto statement in C allows you to jump to a different point in the program’s code. It’s often considered to be a controversial feature of the language, as it can lead to unreadable and difficult-to-debug code.

Syntax:
The basic syntax of the goto statement in C is as follows:

goto label;

// ...

label: statement;

Here, label is an identifier that you’ve defined in your program’s code, and statement is a statement that you want to execute when the goto statement is encountered. When the goto statement is executed, the program will jump to the location in the code where the corresponding label appears, and execution will continue from there.

Example:
Here’s an example of using a goto statement in C:

#include <stdio.h>

int main() {
    int i = 1;

    loop:
    printf("%d\n", i);
    i++;

    if (i <= 10) {
        goto loop;
    }

    return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

In this example, the goto statement is used to create a loop that prints the numbers from 1 to 10. The loop label is defined immediately before the printf statement, and the if statement is used to check if the value of i is less than or equal to 10. If i is less than or equal to 10, the goto statement is executed, and the program jumps back to the loop label. This loop will continue until the value of i is greater than 10.

While the goto statement can be useful in some cases, it’s generally recommended to avoid using it in your code, as it can make the code harder to read and debug. Instead, it’s often better to use loops and conditional statements to control the flow of your program.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.