What goto statement can do in C?

Goto statement is used to transfer the control of the program to a label which is predefined. Goto is a keyword in C which can repeat some part of code for a particular condition. For this it is known as jump statement. We can use this statement inside any block of program to execute some code which is inside a label. In this article we will see some programs with goto keyword and try to describe how they works.

Use & syntax of C goto statement for C

C goto statement is used to jump another code inside our program. However, it is not recommended to use this statement as it makes the program more complicated. But it is still in practice among programmers.

Here is the syntax of goto statement in C.

label:
// code to execute inside the label;
goto label;   // it will execute the code inside the label

C program using goto statement

// use of goto statement in C
#include <stdio.h>
int main(){
    int i = 1;

    print:     // this is the label
        printf("First label\n");
        i++;
    if(i < 5){
        goto print;    // calling label print
    }
    printf("\nCode to execute bellow.\n");

return 0;
}

Here we see that when i < 5, the goto keyword is calling print label. So, the compiler will execute the code inside the label “print”. But when i >= 5, the compiler will go bellow the if block and print other portion of code. So, the output will be as the following;

goto statement in c, goto statement in a program

C loops & goto

// program to use of goto statement in C
#include <stdio.h>
int main(){
  int a, b, c;
  for(a = 1; a < 10; a++){
    for(b = 1; b < 5; b++){
      for(c = 1; c < 4; c++){
        printf("%d %d %d\n",a,b,c);
        if(b == 4){
          goto outside;    // go to the label outside:
        }
      }
    }
  }
  outside:       // label outside
  printf("This is from outside of loop.\n");
return 0;
}

Output of this goto statement program

Previous page:  Continue statement in C

Next pageArray in C programming