C goto

Summary: in this tutorial, you will learn about C goto statement, which is an unconditional jump statement that allows you to any specified location in the program.

C gotoIntroduction to C goto statement

The goto statement is one of C’s branching, or unconditional jump, statements. Whenever the program reaches a goto statement, the execution jumps to the location specified by the goto statement. We call the goto statement is an unconditional statement because whenever the program encounters a goto statement, the execution of the program branches accordingly, which does not depend on any condition like the if statement.

The following illustrates the syntax of the goto statement:

The label specified after the goto statement is the location where the execution is going to branch. The label statement starts with an identifier, and then a colon ( :),  and then a statement, and ends with a semicolon ( ;) as follows:

The statement can be null therefore the label statement can be as follows:

A goto statement and its target, or label, can be in a different block but they are must be in the same function.

C goto statement example

The following example illustrates how to use the goto statement.

How it works.

  • First, we ask the user to enter a number between 0 and 10.
  • Second, we loop from 1 to 10, if we found the input number, we jump to the end label and display a message. If the user enters a number that is not in the range of (0,10) the loop is terminated normally.

When to use C goto statement

It is good practice to use the break, continue and return statement instead of the goto statement whenever possible. If the goto statement is overused, it makes the code unreadable and more difficult to troubleshoot when the error occurs.

Because the break statement only exits one loop level, a goto statement may be used to exit a loop from a nested loop. For example:

Another good example of using the C goto statement is to separate the main logic from the error handling logic. See the following example:

In the f() function above, instead of handling errors in various parts of the function, we use the goto statement and the handle_errors() function to separate the logic.

In this tutorial, we have shown you how C goto statement works and when to apply it in your programming context.

  • Was this tutorial helpful ?
  • YesNo