C Tutorial C References

C - goto Statement



In C, goto is a jump statement and sometimes also referred as unconditional jump statement. It can be used to jump from goto to a labeled statement within the same function. The target label must be within the same file and context.

Please note that the use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, and hence making the program hard to understand and modify.

Syntax

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

In the above syntax, label is a user-defined identifier and it can be set anywhere in the C program above or below to goto statement.

Flow Diagram:

C goto statement

Example:

In the example below, the goto statement is used to display message based on the value of variable x. The program first checks whether the variable x is even or odd and then goto statement is used to display the message based on even/odd assessment.

#include <stdio.h>
 
static void checkNumber(int x) {
  if (x%2 == 0)
    goto evenNumber;
  else
    goto oddNumber;
  
  evenNumber:
    //print the message and exit the function
    printf("%i is an even number.\n", x);
    return;  
  oddNumber:
    //print the message and exit the function
    printf("%i is an odd number.\n", x);
    return;  
}

int main (){
  checkNumber(10);
  checkNumber(13);
  checkNumber(-10);
  return 0;
}

The output of the above code will be:

10 is an even number.
13 is an odd number.
-10 is an even number.