5.4 — Goto statements

The goto statement is a control flow statement that causes the CPU to jump to another spot in the code. This spot is identified through use of a statement label. The following is an example of a goto statement and statement label:

In this program, the user is asked to enter a non-negative number. However, if a negative number is entered, the program utilizes a goto statement to jump back to the tryAgain label. The user is then asked again to enter a new number. In this way, we can continually ask the user for input until he or she enters something valid.

In the section on variables, we covered three kinds of scope: local (block) scope, file scope, and global scope. Statement labels utilize a fourth kind of scope: function scope. The goto statement and it’s corresponding statement label must appear in the same function.

There are some restrictions on goto use. For example, you can’t jump forward over a variable that’s initialized in the same block as the goto:

In general, use of goto is shunned in C++ (and most other high level languages as well). Edsger W. Dijkstra, a noted computer scientist, laid out the case in a famous but difficult to read paper called Go To Statement Considered Harmful. Almost any program written using a goto statement can be more clearly written using loops. The primary problem with goto is that it allows a programmer to cause the point of execution to jump around the code arbitrarily. This creates what is not-so-affectionately known as spaghetti code. Spaghetti code has a path of execution that resembles a bowl of spaghetti (all tangled and twisted), making it extremely difficult to follow the logic of such code.

As Dijkstra says somewhat humorously, “the quality of programmers is a decreasing function of the density of go to statements in the programs they produce”.

Rule: Avoid use of goto unless necessary

5.5 -- While statements
5.3 -- Switch statements

18 comments to 5.4 — Goto statements

  • Tom

    Alex -

    I am really enjoying this tutorial. May I suggest that this section be renamed ” 5.4 รขโ‚ฌโ€ Goto statements (and why they are evil)”?


    Also, you might want to make your reference to “spaghetti code” (in bold) into a link:

  • rohan

    i entered the code which you gave for finding the sqrt.
    it obviously worked fine
    however when i typed in “-9-” it kept on printing “Enter a non-negative number” continuously (i know i shouldnt have done this!!)
    can you pliz tell me what is actually happening!

    • Sure. The first time through, it asks you to enter a #, so you type in “-9-“. It extracts “-9″ into the dX variable, leaving the trailing “-” sign still in the input buffer.

      Because (dX < 0.0) is true, it loops back to the tryAgain label. This time, it tries to extract the "-" into dX, which fails, so dX keeps it's previous value of -9. This causes it to loop again (and again, and again).

      Ideally we should check to make sure the extraction operator (>>) succeeded, but that’s beyond the scope of this tutorial. I believe I cover how to do this in chapter 13, which is when the tutorial delves into I/O issues.

  • fdsafdas

    In The second line… I think you mean “through” instead of “though”.

    “This spot is identified though use of a statement label.”

    [ Indeed! Thanks. -Alex ]

  • spock

    aaaah…. I remember my first ever code as a 7 year old written in Basic was a goto loop.
    I wrote it using a ZX spectrum 48k computer my parents bought me in ’84. My code was:

    10 Print “Hello Richard”
    20 Goto 10

    I thought I was brilliant…


  • @spock

    I have a similar first memory. Virtually the same code, apart from I printed “Stephen” and I did it on my Amstrad CPC in 1987 :)

  • Red Gray

    I’ve found just a few instances where I found goto helpful. But it is indeed helpful. On the ASM level when the program is compiled, there’s a WHOLE lot of goto-ish jumping going on. The idea of not using goto in higher level programming is just giving you less rope to hang yourself with.

  • Freyr

    Thanks for the Tut. Could you also give a typical example about how to avoid a goto-label by using a loop?
    That’s of interest to me, because after inheriting some C++ Code (coded with MS Vis. C++), I started to learn Cpp some 3 months ago (your tutorials could have saved me 2 months!). The code has a goto-label in it, which seems to conflict with Qt-IDE( & g++ compiler) since I must placed the Qt-code in curly brackets to avoid Compile error “crosses initialization of…”

    • #include <iostream>
      #include <cmath>

      int main()
      using namespace std;
      tryAgain: // this is a statement label
      cout << "Enter a non-negative number";
      double dX;
      cin >> dX;

      if (dX < 0.0)
      goto tryAgain; // this is the goto statement

      cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;

      Could be made

      #include <iostream>
      #include <cmath>

      int main()
      using namespace std;
      double dX;
      while (true)
      cout << "Enter a non-negative number";
      cin >> dX;
      if (dX > 0.0)
      cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
      cin >> dX;

      Sure, it’s not the best example in the world, but hey.

  • hiiiiiiiiii. this tut. helps very much and Thank u for helping me in goto statement. this statement helps me much. as i calculate sqr.


  • Kaonashi

    Hahaha, this reminds me of the basic programming I used to do when I was a teen. Every time I wanted to add something to my program (an addition or even a correction), I’d insert a GOTO statement which went to a new section of linenumbers at the end of the program and deal with the problem there. Spaghetti-coding at it’s worst.

  • Retro World

    on the first code of the goto, there should be a

    in the main() function.

  • Canute

  • Karl

    It would have been nice to just make the compiler a little more intelligent so that it would check for accesses to a variable whose initialization was skipped by a goto.

    When dealing with C interfaces, goto helps make the code MUCH easier to read and follow when used as a short-circuit to cleanup code after an error condition is encountered, especially when you have a long chain of code that is dependent on a successful return value of the previous function call, which is itself dependent on an earlier call, and so on (as tends to happen when dealing with system-supplied opaque data types). The alternative is a big mess of nested, error prone if-then-else statements to handle cleanup and error logging, or throwing an artificial exception to be caught within the same method (essentially a glorified goto).

    Indeed, even Dijkstra concedes the use of goto in abort clauses:

    “One can regard and appreciate the clauses considered as bridling its use. I do not claim that the clauses mentioned are exhaustive in the sense that they will satisfy all needs, but whatever clauses are suggested (e.g. abortion clauses) they should satisfy the requirement that a programmer independent coordinate system can be maintained to describe the process in a helpful and manageable way.”

  • Hi,
    Ya this is good example for understanding GOTO Statement…but i have another example it’s so easy to understand how goto work and we can see result easily ok….thanks a lot for giving us a most useful information about c++…

  • ProgrammerJupiter

    I was just curious if it was possible to call the goto a place mentioned after goto. I know this rly is illogical but i want to bypass certain if statements, if possible

  • Rancho

    Woow, this is good. please i need an example of replace(),erase() and find() funtion. thanks

Leave a Comment




10 + fourteen =

Put C++ code inside [code][/code] tags to use the syntax highlighter