The goto statement in C

    The goto statement moves the execution of the program to another statement. The transfer of the control is unconditional and one-way.

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!

Using goto statement to jump to a label

Syntax and rules

    goto labelName;
    ...
    labelName:
    “some statement to be executed”

The label :

  • Must be defined within a function
  • Each label in one function must have a unique name. It cannot be a reserved C word.
  • C has a separate namespaces for identifiers and labels, so you can use the same name for a variable and a label.
  • Must be followed by a statement. We call it a “labeled statement”.
  • Has function scope. Therefore the label:
       - must have a unique name within that function.
       - is not accessible outside the function, where it was defined.

    When the code reaches the goto statement, the control of the program “jumps” to the label. Then the execution continues normally.

    If the execution reaches the labeled statement without a jump the program will execute it just like any other.

Code examples

Jumping out from nested loop:

    void exitFromNestedLoops(int rows, int columns)
    {
        int row, column;
        for(row = 0; row < rows; row++)
        {
            for(column = 0; column < columns; column++)
            {
                if((row+column) > 20)
                    goto exit;
                printf("%2d ", row + column);
            }
            printf("\n");
        }
        exit:
        printf("Exit\n");
    }

Creating a loop:

    void loopUsingGoto()
    {
        int i = 0;
        begin:
        printf("i = %d\n", i);
        i++;
        if(i >= 10)
            goto end;
        goto begin;
        end:
        printf("quit\n");
    }

    The above examples are available for download in this zip file. It contains the source file(main.c) that you can use to run the examples.

Good coding practice:
   Any program that uses the goto statement could and most likely should be redesigned to accomplish the task without it. You can use break, continue and return instead. Pretty much all developers consider the use of goto as bad coding practice. It ruins the code readability and makes debugging and understanding the code harder.

    For my 6 years experience with different programming languages and technologies, there was only 1 (one) case where I chose to use goto. And that was a very specific situation with script code embedded in a description architecture.

See also:

Previous keyword: for

Next keyword: if

Do you learn better from video?

Learn faster with deeper understanding!
The "Computer programming for beginners" course is the perfect place to begin with programming.

Start now!


› goto

Did this help? Support me with your vote ;-)

Did this help?