C Programming Tutorial
About Lesson

C goto statement

In this tutorial, we will learn about goto statement and its working and why should it be avoided In C programming with the help of some examples.


goto statement

The goto statement is a jump control statement that allows us to transfer control of the other part of the program with the help of a label.

Syntax :

goto label;
..........
..........
label:
statement;
..........

How does the goto statement work?

  • The label is an identifier. When goto label; is encountered, the control of program jumps to label: and executes the code below it.

Note : We can use label anywhere in that function where the goto statement is used.


goto statement Flowchart

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

Example: goto Statement

// This program to check if you are 18 or not using goto statement.
# include <stdio.h>
int main(){
  noteligible:
  int age;
  printf("Enter Your age: ";
  scanf("%lf",age);
  if(age < 18){
    printf("You are not eligible for voting!\n");
    goto noteligible;
  }
  else{
    printf("You are eligible for voting!");
  }
  return 0;
}

Output

Enter Your age: 13
You are not eligible for voting!
Enter Your age: 26
You are eligible for voting!

Reasons why we Avoid goto Statement

  • The goto statement gives power to jump to any part of program but, makes the logic of the program complex and tangled.
  • The problem with using goto statement is that it is easy to develop program logic that is very difficult to understand, even for the original author of the code.
  • In modern programming, goto statement is considered a harmful construct and a bad programming practice.
  • It is easy to get caught in an infinite loop if the goto point is above the goto call.
  • The goto statement can be avoided in most of C program with the use of break and continue statements.
error: Content is protected !!