Language Selector

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 its corresponding statement label must appear in the same function.

There are some restrictions on the use of goto statements. 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. 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 is code that 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”.

Goto statements are common in some older languages, such as Basic or Fortran, and even used in C. However, in C++, goto statements are almost never used, as almost any code written using a goto statement can be more clearly written using other constructs in C++, such as loops, exception handlers, or destructors (all of which we’ll cover in future lessons).

Rule: Avoid use of goto statements unless necessary

5.5 -- While statements
5.3 -- Switch statements

31 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.

  • 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 :)

    • Tomboy

      @spock, @Steve

      How interesting. I also wrote a similar program as a kid, but in the 90s. My second program was a text menu of options which allowed the user to choose which one of four different ways they wanted to get lost in an endless loop :)

      I’m not sure if all new programmers go through a stage of doing pointless things for amusement, but I do know that when I showed the program to my mum she looked at me like she was questioning my mental health.

      I prefer to think that my fascination with endless loops was simply a young fascination with the concept of infinity or, er, something intelligent like that…

  • 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…”

    • Could be made

      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.

  • 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.”

    • Alex

      C programmers often use goto in places where cleanup is needed after an error condition.

      In C++, this is not recommended, as better and more robust mechanisms exist, such as exception handling and destructors.

  • 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++…

    • Alex

      It’s clearer without the goto:

  • Todd

    Your link to "Go To Statement Considered Harmful" seems to be outdated/inaccessible. I could find the paper only through the search bar in the link you provided)

  • Label is a mark used to tell the machine that it should restart execution from this point, if a goto statement occurs. Am I right?

    It’s still unclear to me why this doesn’t compile. The above code compiles fine if  x is left uninitialized. Will you please elaborate what’s happening here?

    • Alex

      You can’t use a goto to move forward past a variable initialization. If you jump over the initialization of x = 5, then what would you expect x += 3 to do?

  • Ammm…if  goto moves forward the initialization of x in the above line, doesn’t it mean that definition of x was also skipped. And if definition(declaration) is skipped, why compiler doesn’t throw any error message (undefined variable x or something like that) and only says invalid forward jump?

    • Alex

      Variable definitions (without initialization) are not actually executed. Storage allocation for variables happens at compile time, not runtime, so the variable will still exist even though C++ jumped over it at runtime.

      It’s interesting to note that if this were a class instead of a fundamental data type, the constructor for the class wouldn’t not get executed if the variable’s definition was jumped over, even though memory for the class would be allocated!

  • goto is clear. Thank you sooooo much Alex.

  • Jiri

    Sooo, goto is infact a while loop, the same as for loop is in fact while loop. You only need to play with conditions a bit. It’s nice how almost everything can be reduced to if and while 😀

  • Jim


    In the first code on this lesson you used goto tryAgain; and tryAgain: Is the goto statement always followed by a semi-colon and the statement label always followed by a colon?. Are there any restrictions on what the name can be?
    Like goto point1; point1:

    • Alex

      Yes, the goto statement is always terminated by a semicolon (because it’s a statement). The statement label uses a colon because it’s a label.

      I’m not sure what restrictions there are on naming goto labels, but I suspect you can’t name them a reserved word.

  • #include<iostream.h>

    int main()
      int n=10;
      cout<< n << " \n ";
      if (n>0) goto loop;
    what’s wrong with my program I cant run my homework is a program that will display the following
    please help me thanks a lot

    • Alex

      Structurally and logically, your program is fine. However, your program has a few issues:
      1) On modern compilers, you should be including iostream, not iostream.h, and conio.h has been deprecated.
      2) n- should be n-
      3) cout needs to be prefixed with std::
      4) BTOOM!!!\n needs to be in double quotes, since it’s a string.

  • siyi

    In C another justifiable usage of goto is to break out of nested loops. Is this still the case in C++?

Leave a Comment

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




16 − 3 =