Search

7.6 — Goto statements

The next kind of control flow statement we’ll cover is the unconditional jump. An unconditional jump causes execution to jump to another spot in the code. The term “unconditional” means the jump always happens (unlike an if statement or switch statement, where the jump only happens conditionally based on the result of an expression).

In C++, unconditional jumps are implemented via a goto statement, and the spot to jump to 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.

Here’s a sample run of this program:

Enter a non-negative number: -4
Enter a non-negative number: 4
The square root of 4 is 2

Statement labels have function scope

In the chapter on object scope (chapter 6), we covered three kinds of scope: local (block) scope, file scope, and global scope. Statement labels utilize a fourth kind of scope: function scope, which means the label is visible throughout the function even before its point of declaration. The goto statement and its corresponding statement label must appear in the same function.

While the above example shows a goto statement that jumps backwards (to a preceding point in the function), goto statements can also jump forward:

This prints:

cats

Beyond the jumping forward, there are a couple of interesting things worth mentioning in the program above.

First, note that statement labels must be associated with a statement (hence their name: they label a statement). Because the end of the function had no statement, we had to use a null statement so we had a statement to label. Second, we were able to jump to the statement labeled by end even though we hadn’t declared end yet due to statement labels having function scope. No forward declaration of statement labels is necessary. Third, it’s worth explicitly mentioning that the above program is poor form -- it would have been better to use an if statement to skip the print statement than a goto statement to jump over it.

There are two primary limitations to jumping: You can only jump forward or backward within a single function (you can’t jump out of one function and into another), and if you jump forwards, you can’t jump forward over the initialization of any variable that is still in scope at the location being jumped to. For example:

Note that you can jump backwards over a variable initialization, and the variable will be re-initialized when the initialization is executed.

Avoid using goto

Use of goto is shunned in C++ (and other modern high level languages as well). Edsger W. Dijkstra, a noted computer scientist, laid out the case for avoiding goto 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 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”.

Almost any code written using a goto statement can be more clearly written using other constructs in C++, such as if statements and loops. One notable exception is when you need to exit a nested loop but not the entire function -- in such a case, a goto to just beyond the loops is probably the cleanest solution.

Best practice

Avoid goto statements (unless the alternatives are significantly worse for code readability).


7.7 -- Intro to loops and while statements
Index
7.5 -- Switch fallthrough and scoping

79 comments to 7.6 — Goto statements

  • GFK

    Goto is love. Goto is life.
    http://www.iso-9899.info/wiki/Cleanup

    https://stackoverflow.com/questions/245742/examples-of-good-gotos-in-c-or-c

  • You know, I learned coding in old BASIC, where you hardly could live without GOTO (in later BASIC versions WHILE loops were present, but in the very early days... nope). And now I've used programming languages in which "GOTO" (nor any equivalent) is present, and I can say, that it's a wonderful experience to be forced to never use "GoTo" again, so you are forced to learn to live without it.

    Oh by the way, I read somewhere that Dijkstra may have been one of the guys who had the most harsh critics on the "GOTO" command (but then again, he also said that teaching COBOL should be considered a criminal offense, because it cripples the mind), but many of his own source codes were swamped with GOTO commands. What does that tell us?

    • Alex

      Didn't your old BASIC programs use GOSUB as well?

      All your anecdote tells me is that old habits are hard to break. This tutorial series is replete with examples of this. :)

  • Goto statements can be used badly by noob programmers sometimes, In OOP, we can write better solutions rather than using goto, but I think you should add good uses of it too.
    According to Bjarne Stroustrup, in his C++ Programming Language book, below is an example of a "good use" of goto in nested loops:

    https://stackoverflow.com/a/245801/3909447

    Good website by the way, for newbies.

  • Yuk! reminds me of BASIC programming in the '80s.  Even then the use of a GOTO statement was frowned upon and GOSUB was a much better practice.

    Consider:

    Messy but probably similar to the first program everybody created.

    Think I shall leave GOTO out of my vocabulary....

  • Maxixxx

    Lots of things can be done with no goto statements, like this example:

    calc.cpp

    main.cpp, using the goto statement

    main.cpp without the goto statement

    • nzqrc

      I think in this case a while loop would still look nicer.
      Something like this: (I haven't tested for syntax errors!)

  • The Perplexed Programmer

    SO basically it'a like a loop?
    If not, what are the differences between the two?

    • Alex

      Goto statements are more flexible than loops, as they can jump either backwards or forwards. If you jump backwards to somewhere in the same function, then the goto acts kind of like a loop (and you might as well use a loop). Jumping forward is not something I see done very often, typically only for error handling purposes.

      • The Perplexed Programmer

        Thanks!!

      • Anon

        techniclly speaking, loops *are* just fancy goto statements.

        BTW, Is there a flag relient goto in c++? I mean, those are the kind of goto statements that are actually good for something (I only ever used jmp when my labels where too far from eachover, while the conditional jamps are a real nice to have)

        BTW2, Is there such a thing as "too far" lables in c++, or does the compiler/linker takes care of it?

  • Woah! I'm really loving the template/theme oof this blog.
    It's simple, yet effective. A lot of times it's very
    hadd to get that "perfect balance" between user friendliness
    and visual appearance. I must say you've done a excellent job with this.
    Also, the blog loads super quick for me on Safari. Excellent Blog!

  • HWANG SEHYUN

    Does the information of statement label store on stack?

  • Brana

    What i would like to add here is the limit to a number of characters that a user can enter JUST for arithmetic part. So, he can just enter one of the following +,/,* or - and not ++++ or +*/- at a same time. I tried:  if(op.length() != 1) and then below is goto tryAgain; but i get an error: request for member 'length' in 'op', which is of non-class type 'char'

  • Darren

    Perhaps the title for this page should be
    "GOTO HELL!!"

  • joe

    Another way I found to do this I learned on accident.
    I called a function to have an integer input that was between a certain range.  I used two bool values to find if the number was within range.  
    I ran an if statement to determine true then returned the value.
    in my else statement i blocked a cout statement asking for a new number to be input, then I returned the function.

    it works great.  Is there a reason as not to use this method?

    [code]
    int getValue()
    {
    std::cout << "It puts the digit in the basket: \n";
    int x;
    std::cin >> x;
    bool value1;
    bool value2;
    if (x < 10)
    value1 = true;
    if (x > 0)
    value2 = true;
    if(value1, value2)
    return x;
    else
    {
    Std::cout << "IT DOES WHAT IT IS TOLD OR IT GETS THE HOSE AGAIN!!!!!";
    return getValue();
    }
    }

    • Alex

      Yes, there are several problems with this.
      1) You shouldn't use the comma operator to test if value1 or value2 are true. Use the LOGICAL OR operator (||).
      2) This function is calling itself, which in and of itself isn't necessarily a problem, but in this case, it's less confusing to use an iterative (loop) method.
      3) 0 is a digit and it is disallowed.
      4) You don't need to use variables for value1 and value2 since each is only used once. Just do the test inline. e.g. if (x < 10 || x > 0) ...

  • i am like wowzies. I hv my class 11th comp exam tomorrow n till the evening I was "I know exactly nothing". This is a really good website. I am really enjoying learning it. keep the work up :). Wish me luck for my exam.

  • siyi

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

  • #include<iostream.h>
    #include<conio.h>

    int main()
    {
      int n=10;
      loop:
      cout<< n << " \n ";
      n--;
      if (n>0) goto loop;
      cout<<BTOOM!!!\n;
      getch();
    }
    what's wrong with my program I cant run my homework is a program that will display the following
    10
    9
    8
    7
    6
    5
    4
    3
    3
    1
    0
    BTOOM!!!
    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.

  • Jim

    Alex,

    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.

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

  • goto is clear. Thank you sooooo much Alex.

  • 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!

  • 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?
    Thanks...:)

    • 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?

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

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

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

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

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

    Thanks.

  • 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..."
    Thanks

    • Could be made

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

      • Jason

        Direct translation would be:

        "endless" loops such as while(true), while(1), etc. should be avoided, i would only use them for main/super-loops.

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

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

  • 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
    Run

    I thought I was brilliant...

    ;)

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

  • 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: http://en.wikipedia.org/wiki/Spaghetti_code

Leave a Comment

Put all code inside code tags: [code]your code here[/code]