English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C Language goto Statements

In this tutorial, you will learn how to create goto statements in C programming. You will also learn when to use goto statements and when not to use them.

The goto statement allows us to transfer control of the program to a specified label.

Syntax of goto statement

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

label is an identifier. When goto encounters this statement, control of the program jumps to label: and begins executing the code.

Example: goto statement

//The program calculates the sum of positive numbers
//If the user enters a negative number, display the total and average.
#include <stdio.h>
int main() {
   const int maxInput = 100;
   int i;
   double number, average, sum = 0.0;
   for (i = 1; i <= maxInput; ++i) {
      printf("%d. Enter a number: ", i);
      scanf("%lf", &number);
      
      //If the user enters a negative number, jump
      if (number < 0.0) {
         goto jump;
      }
      sum += number;
   }
jump:
   average = sum / (i - 1);
   printf("Sum (Total) = %.2f\n", sum);
   printf("Average (Average) = %.2f", average);
   return 0;
}

Output result

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum (Total) = 16.60
Average (Average) = 5.53

Reasons to avoid or use goto statements sparingly

Using goto statements can lead to code that is error-prone and difficult to follow. For example,

one:
for (i = 0; i < number; ++i)
{
    test += i;
    goto two;
}
two: 
if (test > 5) {
  goto three;
}
... .. ...

Additionally, the goto statement allows you to perform bad operations, such as jumping out of a range.

Although that may be the case, goto can sometimes be useful. For example: breaking out of nested loops.

Should you use goto?

If you think using goto statements can simplify the program, you can use them. However, goto is rarely useful, and you can also create any C program without using any goto statements.

This is C ++words by its creator Bjarne StroustrupThe fact that 'goto' can do everything is exactly why we don't use it.