C goto Statement

In this tutorial, you will learn how to use goto statements in the C programming language with the help of examples.


The goto statement in C language is used to transfer the control of the program to a predefined label in the same function. This also can be used to repeat some part of the code for a specific condition.

However, the use of the goto statement is highly discouraged these days as it makes it hard to identify the control of the program, making the program complicated and hard to modify. Any program written with the help of the goto statement can be rewritten to avoid them.

Syntax

The syntax of the C goto statement is as follows:

goto label;
..
..
label: statement;

OR

label: statement;
..
..
goto label;

Here, the label can any word or plain text except the C keywords, and the position of the label can be anywhere in the program below or above goto statement.

Flowchart of the C goto statement

c goto

Example

Let’s check a simple example to use the goto statement in the C programming language.

// C program to print from 1 to 10 using the goto
#include <stdio.h>
int main()
{
    int i = 1; // Local variable declaration

label: 
    printf("%d ",i);
    i++;

    if (i <= 10)
        goto label;    

    return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

When you should use the goto?

Whenever you think that the program will simplify using the use of goto statement, you can use it. For example, to come out from the multiple nested loops multiple break statements are needed. In this case, you can use goto statement as below:

#include <stdio.h>  
int main()   
{  
  int i, j, k;    
  for(i=1;i<10;i++)  
  {  
    for(j=1;j<10;j++)  
    {  
      for(k=1;k<10;k++)  
      {  
        printf("%d %d %d\n",i,j,k);  
        if(j == 2)  
        {  
          goto exit;   
        }  
      }  
    }  
  }  
  exit:   
  printf("Came out of the loop.");   
}

Output

When the above code is compiled and executed the following output will produce.

1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 1 7
1 1 8
1 1 9
1 2 1
Came out of the loop.

Please get connected & share!

Categories

Advertisement