Goto Statement in C

The goto statement in C Programming is useful to alter the flow of a program. When the compiler reaches the goto statement, then it will jump unconditionally ( both forward and backward ) to the location specified in the goto statement (we called it as a label).

Unlike the Break and Continue Statement, the goto statement in C doesn’t require any If Statements to perform.

Goto Statement Syntax

The label specified after the goto statement in C Programming is the location where we place the statements to execute. From the below syntax, you can understand that we can place the label anywhere in the program. It doesn’t matter if you put before the goto statement or after.

Goto Statemen in C Syntax

Goto Statement in C Example

This program for c goto allows the user to enter his/her individual subject marks. Next, it will check whether the person is pass or fail using Goto Statement.

/* Goto Statement in C Programming example */

#include <stdio.h>

int main()
{
  int Totalmarks;

  printf(" \n Please Enter your Subject Marks \n ");
  scanf("%d", & Totalmarks);

  if(Totalmarks >= 50)
   {
     goto Pass;
   }
  else
     goto Fail;
  
  Pass:
     printf(" \n Congratulation! You made it \n");

  Fail:
     printf(" \n Better Luck Next Time \n"); 

 return 0;
}
Goto Statement in C Programming

In the above goto statement in c program, Pass and Fail are the labels we used. First, we declared integer variable Totalmarks

int Totalmarks;

Please refer to Break, Continue Statement, and If Statement articles in C Programming.

In the next line, Printf statement will ask the user to enter his/her total marks. scanf statement will store the user-specified value in Totalmarks variable

  printf(" \n Please Enter your Subject Marks \n ");
  scanf("%d", & Totalmarks);

In the next line, we used If Else Statement in C to check whether the user entered value is greater than or equal to 50.

if(Totalmarks >= 50)
   {
     goto Pass;
   }
  else
     goto Fail;

If the condition is TRUE, C Goto statement inside the If block will take the compiler to the Pass label and executed the statements inside the Pass label

 printf(" \n Congratulation! You made it \n");

Else (If the condition is FALSE), then Goto statement inside the Else block will take the compiler to the Fail label. Next, it executes the statements inside the Fail label.

printf(" \n Better Luck Next Time \n");

NOTE: Although all the programming languages support goto statements. However, it is always good practice to avoid using it or at least minimize the usage. Instead of using the goto statement, we can use alternatives such as Break and Continue statements.