Goto Statement in C
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.
In this article, we will understand the “goto” statement in C and discuss its syntax, usage, and applications through examples.
Table of Content
- What is Goto Statement in C?
- Ways of Implementing Goto Statement in C
- Why must the Use of the Goto Statement be Avoided?
So, without further delay, let’s get started!
Best-suited C / C++ courses for you
Learn C / C++ with these high-rated online courses
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.
Flowchart
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.
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;}
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;}
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.
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