C goto Statement

The goto statement is a jump statement, also reffered as unconditional jump statement. It is used to jump from the 'goto' to a labeled statement in the same function. The syntax of goto statementis as follows :
goto label;
....
....
....
label:
  statement;
  ........
  ........
At above, the label is an identifier, when goto statement is encountered, control of the program jumps to label: and starts executing the code.


Now lets see an example of goto statement.
#include <stdio.h>

int main() {
  int c = 0;

  Loop:
    printf("Hello world!\n");
    c++;
    if(c < 5) { goto Loop;}

  return 0;
}
Output :

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

Another example of goto statement.
#include <stdio.h>

int main() {

  int num;
  printf("Enter a number : ");
  scanf("%d", &num);

  if(num < 10) {
    goto label1;
  } else {
    goto label2;
  }

  label1:
    printf("%d is less then 10.\n", num);
    return 0;

  label2:
    printf("%d is greater then 10.\n", num);

  return 0;
}
Output :

Enter a number : 5
5 is less then 10.

Note : The use of goto statement in C language is highly discouraged, because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Next Topic :