top

Search

C Tutorial

.

UpGrad

C Tutorial

goto statement in C

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!

Goto Statement Syntax in C

Given below is the goto statement in C syntax:

Syntax1      |   Syntax2
----------------------------
goto label;  |    label:  
.            |    .
.            |    .
.            |    .
label:       |    goto label;

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.

Methods to Implement Goto Statement in C

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>

int main()
{
    statement1;
    ...
 
    label_name:
        statement2;
        statement3;
        ...
        if(condition)
            goto label_name;
 
    return 0;
}

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>

int main()
{
    // Print numbers from startValue to endValue
    
    // Initialize startValue and endValue variables
    int startValue = 1, endValue = 10;
    
    // Initialize variable to keep track of the current number to be printed
    int current = startValue;
    
    // Define the label
    print_line:
        
        // Print the current number
        printf("%d ", current);
        
        // Check if the current number has reached the endValue
        // If not, it means there are still more numbers to be printed
        if(current < endValue)
        {
            // Increment the current number
            current++;
            // Use goto to repeat the printing process
            goto print_line;
        }
        
        // If the current number has reached the endValue, the statements inside the if block will not be executed
        // The program terminates
        
    
    return 0;
}

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>

int main()
{
    statement1;
    ...
    
    if(condition)
        goto label_name;
    
    statement2;
    ...
    
    label_name:
    
        statement3;
        statement4;
        ...
   
    return 0;
}

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>
int main()
{
    // Find the ceiling division of dividend by divisor
    
    // Initialize dividend and divisor
    int dividend = 5, divisor = 2;
    
    // Variable to store the division result
    int quotient = dividend / divisor;
    
    // If dividend is perfectly divisible by divisor, just print the result
    if (dividend % divisor == 0)
    {
        // The goto statement transfers the control to the print_line label
        goto print_line;
    }
    
    // Otherwise, add 1 to the quotient for the ceiling division
    quotient += 1;
    
    // Define the label
    print_line:
        
        printf("%d", quotient);
    
    return 0;
}

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.

Goto Statement: How Does it Work in C?

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.

Understanding the Goto Statement in C Using a program

Let's examine a program in C that calculates and outputs the absolute value of any given integer. 

#include <stdio.h>
#include <math.h>
int main()
{
    // Initialize a number for which the absolute value is to be printed
    int number = -11;
    // If the number is already non-negative, print it directly
    if (number >= 0)
    {
        // The goto statement transfers the control to the positive label
        goto positive;
    }
    // To make the number non-negative, multiply it by -1
    number = number * (-1);
    // Define the positive label
    positive:
        printf("The absolute value is %d", number);   
    return 0;
}
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.

Goto Statement in C Example

#include <stdio.h>
int main() {
   const int maxInput = 100;
   int count;
   double input, average, sum = 0.0;
   for (count = 1; count <= maxInput; ++count) {
      printf("%d. Enter a number: ", count);
      scanf("%lf", &input); 
      // Jump to the "jump" label if the user enters a negative number
      if (input < 0.0) {
         goto jump;
      }
      sum += input;
   }
   // Label "jump" is defined here
   jump:
   average = sum / (count - 1);
   printf("Sum = %.2f\n", sum);
   printf("Average = %.2f", average);
   return 0;
}

Output: 

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53

When Should We Use the goto Statement?

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>  
int main()   
{  
  int num1, num2, num3;    
  for(num1 = 0; num1 < 10; num1++)  
  {  
    for(num2 = 0; num2 < 5; num2++)  
    {  
      for(num3 = 0; num3 < 3; num3++)  
      {  
        printf("%d %d %d\n", num1, num2, num3);  
        if(num2 == 3)  
        {  
          goto end_loop;   
        }  
      }  
    }  
  }  
  end_loop:   
  printf("Exited the loop");   
}
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
Exited the loop

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.

Goto Statement in C: Advantages & Disadvantages

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.

Best Practices

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.

Common mistakes to avoid in the goto statement in C:

  • Overuse: Using goto excessively can make the code difficult to understand and maintain. It is recommended to use structured control flow constructs like loops and conditionals whenever possible.

  • Jumping into blocks: It is considered bad practice to jump into or out of a code block using goto. This can lead to confusion and unexpected behaviour. It is best to structure the code to avoid the need for such jumps.

  • Variable scope issues: Jumping to a label can bypass variable declarations and lead to scope-related problems. Ensure that variables used after a goto statement are properly initialized and in the correct scope.

  • Unreachable code: Improper use of goto can result in unreachable code sections, causing potential logic errors. Carefully analyse the flow of the program to ensure all parts are reachable and necessary.

Controversies

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. 

Conclusion

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!

FAQs

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.

Leave a Reply

Your email address will not be published. Required fields are marked *