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 it (we called it as a label).

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

Goto Statement Syntax

The label specified after the goto statement in C Programming is the location where we place the code block 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 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

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

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

In the next line, we used If Else 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 block of code inside the Pass label

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

Else (If the condition is FALSE), then the code inside the Else block will take the compiler to the Fail label. Next, it executes the code block 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 this, we can use alternatives such as Break and Continue.