Tutorial Playlist
The jump statement in C, known as the goto statement, allows you to transfer program control to a specified label. This means you can repeat a specific part of the code based on a condition. Goto can be leveraged to break out multiple loops, which is not possible with a single break statement. It's important to prioritise writing clean and readable code, especially when working on projects with multiple developers.
The goto statement in C plays a significant role in programming as it provides a means to control the flow of execution within a program. While it is generally advised to use structured control flow constructs like loops and conditionals, there are several situations where the goto statement is deemed advantageous. It allows for non-linear control flow, enabling programmers to handle complex scenarios and break out of multiple nested loops.
However, caution must be exercised when using goto to maintain code readability and prevent the creation of intricate and hard-to-maintain code structures.
Let us explore goto statement in depth to comprehend its appropriate and limited usage in C!
Given below is the goto statement in C syntax:
Syntax1 Â Â Â | Â Syntax2 |
The above syntax instructs the compiler to goto or jumps to a statement marked as a label. In this case, the label is a custom identifier that signifies the target statement. The statement immediately following the label, denoted as 'label:', serves as the destination statement. It's worth noting that the 'label:' can also appear before the 'goto label;' statement in this syntax.
There are two different methods which we can use to implement goto statements in C, each with its own characteristic behaviour. The first style involves declaring the label above the goto statement, while the second style declares the label after the goto statement.
In the first method, the program's control of the flow shifts from a lower part of the code to the upper part, exhibiting a loop-like behaviour.
Let's look at the syntax to understand it better.
Style 1: Transferring Control: Down to the Top
#include <stdio.h> |
In the pseudo-code above, when the condition is true, the program's control to execution will be sent to the label_name. Let's consider an example scenario where we may utilise this logic.
Example 1: Printing numbers using the goto statement
#include <stdio.h> |
Output:
1 2 3 4 5 6 7 8 9 10 |
The given code is a program that prints numbers from a starting value to an ending value using a goto statement to repeat the printing process. It initialises variables for the starting, ending, and current numbers. It then defines a label called print_line as the target for the goto statement. Inside the label, the program prints the current number, increments it if it's less than the ending value, and jumps back to the print_line label. This continues until the current number reaches the ending value. Finally, the program returns 0.
Style 2: Transferring Control: Top to Down
This style follows the same syntax as before, with the only difference being that the label is declared after the goto statement is invoked. Consequently, in this style, the control is transferred to a program section located below the goto statement.
This is the syntax:
#include <stdio.h> |
In the provided pseudo-code, the control is passed to the label block when the condition results to be true. Let's examine an example to illustrate this.
Example 2: To find ceil division of two numbers.
#include <stdio.h> |
Output:
3 |
The code initialises the dividend and divisor variables. It calculates the quotient using integer division. If the dividend is perfectly divisible by the divisor, the result is printed. Otherwise, 1 is added to the quotient for the ceiling division. The program uses a label and the goto statement to control the flow. Finally, the code outputs the quotient, which represents the ceiling division of the dividend by the divisor.
The goto statement in C is a straightforward way to introduce control jumping in C programs. To use the goto statement, we first need to define it using the keyword "goto" followed by a labelname. Once the goto statement is defined, we can specify the labelname anywhere in the program where we want the control to be transferred when the compiler encounters the goto statement. This allows us to navigate different program parts based on specific conditions or requirements.
Let's examine a program in C that calculates and outputs the absolute value of any given integer.
#include <stdio.h> |
The absolute value is 11 |
The code initialises a variable named number. If the number is already non-negative, it is printed directly. Otherwise, the number is made non-negative by multiplying it with -1. The code uses a label and the goto statement to control the flow. Finally, the absolute value of the number is printed.
#include <stdio.h> |
Output:
1. Enter a number: 3 |
The goto statement is typically avoided in programming because it can make code more complex and harder to understand. However, there is one scenario where using goto can be advantageous.
When there is a need to break multiple loops simultaneously using a single statement, the goto statement can be used.. Let's understand this with example:
#include <stdio.h> Â |
0 0 0 |
The goto statement in C can leap from one part of the code to a different one, regardless of the program's flow. Based on the declaration of the corresponding label, calling a goto statement in any program enables us to go to any location within the function.
One important aspect to remember is that goto statements can even take us to a code section that has already been executed, provided that the label is defined before the goto statement. This behaviour distinguishes goto from other jump statements, for instance, a break, that typically transfers execution to a location below the current point of execution.
The goto statement is a feature available in the C language that offers certain advantages to programmers. In C, the goto statement provides simplicity and convenience by allowing programmers to specify the desired jump in the program's flow. The compiler takes care of executing the jump accordingly. This feature is often used by programmers while developing programs.
Despite its advantages, the goto statement has limitations and drawbacks, as it is not present in high-level languages like Java or Python. While it is easy to use, using goto multiple times in a program can complicate it unnecessarily. High-level languages provide alternative constructs like loops to achieve repetitive tasks.
The goto statement does not follow structured programming principles, and its absence in high-level languages is a deliberate design choice to maintain code readability and maintainability.
It is generally advised not to use "goto" statements to jump into code blocks. This is because-
The usage of "goto" statements can result in exceedingly challenging programs to comprehend and analyse. It can also lead to unspecified behaviour. It is generally recommended to avoid using goto statements.
Removing goto from certain code can sometimes result in a rewritten version that is even more perplexing than the original. As a result, limited usage of goto is occasionally advised.
However, it is crucial to note that using goto to jump into or out of a sub-block of code, such as entering the body of a for loop, is never considered acceptable. Such usage is uneasy to comprehend and likely to produce unintended outcomes.
When discussing the topic of goto, people often argue that considering it harmful is an exaggeration. However, the reason behind considering goto as "harmful" is primarily due to its impact on program comprehension, particularly as the complexity of the program increases, even in small programs.
Maintenance of programs that employ goto statements can become a daunting task. Simply stating that "goto is a tool, and tools should be used" is an oversimplified argument. While it's true that a tool can serve a purpose, we have progressed significantly from using tools in simple and outdated ways. In programming, the unstructured jumps facilitated by goto can impede understanding and hinder the development of maintainable code.
Instead, Nested Loops can be utilised as an alternative to goto statements.
Understanding the goto statement in C programming is crucial as it allows for control flow manipulation and can be useful in certain scenarios. While its usage should be approached with caution, knowledge of goto enables programmers to navigate complex situations, break out of multiple loops, or perform specific jumps within code. However, balancing convenience with code readability and maintainability is crucial when deciding to use goto.
In case you wish to dive further into the intricacies of programming, upGrad offers a specialised MS in Computer Science course from Liverpool John Moores University to enhance your comprehension of C programming. Gain expertise in full-stack development, various programming languages, and essential tools to explore countless exciting opportunities post program completion!
1. Is it good to use the goto statement in C?
The `goto` statement is generally avoided in programming due to its complexity in understanding and modifying the control flow of a program. An alternative that does not involve `goto` should be sought out when attempting to write a program.
2. Why do people use goto in C?
Suppose you want to avoid repeating cleanup code and separate error handling from the rest of the program logic. In that case, the 'goto' statement in C may be a good option, as there is no native exception handling mechanism in C.
3. What can I use instead of goto in C?
Instead of using the goto statement in C, loops can be exited or continued using the break and continue statements, respectively.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...