Goto Statement in C

Goto Statement in C

6 mins read1.1K Views Comment
Updated on Mar 20, 2024 18:45 IST

This article covers the “goto” statement in C programming. The article goes on to explain two approaches to using “goto” in C, one where the label is declared before the “goto” statement and the other where it is declared after. The article concludes by summarizing why “goto” statements are discouraged.

The “goto” statement in C is a type of jump statement that allows for a change in the normal flow of the program. The “goto” statement can skip over certain codes or repeat a block by returning to a previously labelled block.

Control Statements in C | Meaning and Types
Control Statements in C | Meaning and Types
Control statements in C are used to determine the order in which the instructions within a program are executed. They are of three types: Selection, Iteration & Jump statements. Think...read more

In this article, we will understand the “goto” statement in C and discuss its syntax, usage, and applications through examples. 

Table of Content

So, without further delay, let’s get started! 

Check out C Programming Online Courses & Certifications

What is Goto Statement in C?

The “goto” statement in C is an example of a jump statement used to change the flow of execution from one block of code to another. It is referred to as an unconditional jump statement. While it can be used to create loops, its main purpose is to control the execution of a program. 

The “goto” statement can change the order in which instructions are executed, but it is generally discouraged due to its potential to decrease the readability and understandability of the code. Sometimes, it can also exit multiple loops instead of using multiple break conditions.

Syntax

The syntax for a “goto” statement in C is shown below

goto label;
...
...
label:
// Code to execute after the goto statement

The label is a unique identifier followed by a colon, and a statement is the code executed when the “goto” statement jumps to that label. 

The “goto” statement can be placed anywhere in the code and, when executed, will transfer control to the labelled statement.

Power Function in C
Power Function in C
Have you ever wondered how mathematical calculations involving exponents are handled in the C programming language? One of the key functions used for this purpose is the pow() function, which...read more
Function in C | About, Types and Examples
Function in C | About, Types and Examples
Have you heard of functions in the C programming language? Let's explore it, including its types and examples in detail! A function in C is a collection of statements designed...read more
User Defined Functions in C | Meaning, Types and Examples
User Defined Functions in C | Meaning, Types and Examples
Have you ever wondered how to customize your programming tasks in C to make your code more organized and reusable? User-defined functions in C allow you to do just that....read more

Flowchart

2023_02_image-31.jpg

As depicted in the flowchart, when the “goto” statement is encountered, the code’s control jumps to the specified label’s location.

If the label is defined below the “goto” statement, the statements between the “goto” statement and the label are skipped.

Alternatively, if the label is defined before the “goto” statement, the statements between the “goto” statement and the label are repeated instead of skipped.

This is illustrated in the image provided.

2023_02_image-32.jpg

Ways of Implementing Goto Statement in C

There are two approaches to using “goto” statements in C. One is where the label is declared before the “goto” statement, and the other is where the label is declared after the “goto” statement.

In the first approach, flow control moves from a lower to an upper part of the code, while in the second approach, flow control moves from an upper to a lower part of the code, potentially skipping some lines in between.

Let’s examine both methods in more detail to gain a deeper understanding.

Approach 1: Transferring Control Down-to-top

In this approach, the label is declared above the call of the “goto” statement. We will demonstrate this more clearly through an example.

Here is a revised and well-defined syntax

#include <stdio.h>

int main() {
    // Example initial statement
    printf("Beginning of the program.\n");

    // Label definition
    label_name: 
        // Statements after the label
        printf("This is statement 2.\n");
        printf("This is statement 3.\n");

        // Example condition for the goto statement
        int condition = 1; // Example condition variable
        if (condition) {
            goto label_name;
        }

    return 0;
}

Let’s consider an example to demonstrate how this logic might be applied.


 
#include <stdio.h>
int main() {
int start = 1, end = 10;
int curr = start;
print_line:
printf("%d ", curr);
if (curr < end) {
curr++;
goto print_line;
}
return 0;
}
Copy code

Output

1 2 3 4 5 6 7 8 9 10 

In this program, the label print_line is declared above the call of the “goto” statement. The program’s control is transferred from the lower to the upper part, thus repeating the statements between the “goto” statement and the label declaration.

Approach 2: Transferring Control Top-to-down

In this approach, the label is declared after the call of the “goto” statement. We will demonstrate this more clearly through an example.

Here is a revised and well-defined syntax

#include <stdio.h>

int main() {
    statement1;
    // ...

    if (condition)
        goto label_name;

    statement2;
    // ...

label_name:

    statement3;
    statement4;
    // ...

    return 0;
}

Let’s consider an example to demonstrate how this logic might be applied.


 
#include <stdio.h>
int main() {
// initialize a and b
int a = 5, b = 2;
// variable to store division
int ans;
// Check if b is not zero to avoid division by zero
if (b != 0) {
ans = a / b;
// if a is perfectly divisible by b, just print it
if (a % b == 0) {
// goto statement directs the code to the print_line label
goto print_line;
}
// else 1 needs to be added to the answer, for ceil division
ans += 1;
} else {
// Handle division by zero error
printf("Error: Division by zero.\n");
return 1; // Non-zero return value to indicate error
}
// defined label
print_line:
printf("%d", ans);
return 0;
}
Copy code

Output

3

In this program, we add one to the answer only if a is not divisible by b; else, we use the “goto” statement to go straight to the label print_line. Thus, in this way, the “goto” statement helps transfer the control from top to down in the code.

Why must the Use of the Goto Statement be Avoided?

The “goto” statement in C should be avoided because it can lead to unstructured and difficult-to-understand code. The flow of control in a program with “goto” statements can be confusing and hard to follow, making it difficult to maintain or modify the code in the future. 

Additionally, “goto” statements can lead to infinite loops, unexpected behaviour, and unexpected results. Using more structured control flow statements like for, while, or if-else instead of “goto” is recommended.

Thus, the “goto” statement in C is a jump statement that transfers control from one part of the code to another. It changes the normal flow of the program, allowing for greater control and customization of the execution sequence.

I hope this article helped you grasp “goto” statements in C. Explore our C articles to learn more about the language and consolidate your knowledge of the fundamentals. 

FAQs

What is the goto statement in C?

The goto statement is a control flow construct in C that allows you to jump to another part of the program. It transfers program control to a specified label within the same function. A label is marked by an identifier followed by a colon (:), and the goto statement is used to jump to that label.

How do you use the goto statement in C?

To use goto, first define a label in your code, then use the goto keyword followed by the label name to jump to it. For example

goto myLabel;
...
myLabel:
   // code to execute after the jump

Why is the goto statement often discouraged in programming?

The goto statement is discouraged because it can make the program's control flow difficult to follow, leading to code that is hard to read and maintain. It can create spaghetti code (complex and tangled code paths), increasing the likelihood of errors and bugs.

Are there any valid uses for the goto statement in C?

While generally avoided, goto can be useful in certain scenarios, such as breaking out of deeply nested loops, error handling in a structured manner, and in some cases, for performance optimizations in low-level programming. However, these use cases are relatively rare, and alternative constructs are often preferred.

What are the alternatives to using goto in C?

C provides structured control flow constructs that can often replace the goto statement, such as break and continue for loop control, and if-else statements and switch cases for conditional branching. Additionally, structured error handling can often be achieved using functions and return values or error codes.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio