Navigation



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:

#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;
}

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:

int main()
{
    goto skip; // invalid forward jump
    int x = 5;
skip:
    x += 3; // what would this even evaluate to?
    return 0;
}

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
Index
5.3 — Switch statements

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

  • [...] 2007 Prev/Next Posts « 5.2 — If statements | Home | 5.4 — Goto statements » Thursday, June 21st, 2007 at 6:41 [...]

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

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


    • #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)
      break;
      }
      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.

    Thanks.

  • 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

     return 0; 

    in the main() function.

  • Canute
     Hello Alex, first off I would just like to thank you so much for taking the time to write this tutorial, it is the best online one I have seen yet. My question is what is a good example of code where you NEED a goto statement? Like Kaonashi said I'm pretty new to programming and I used to use GOTO for everything. It got extremely tedious debugging the code or even adding something else. Thanks in advance -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++…

    #include <iostream.h>
    #include <conio.h>
    
    void main()
    {
    
        int n,x,sum=0,ch;
    tryAgain: // this is a statement label
        cout<<"n Enter any number";
        cin>>n;
    sum=sum+n;
    cout << " Press 1 for Add new Number Or Press any number for exit ";
    cin>>ch;
       if (ch==1)
       goto tryAgain; // this is the goto statement
       cout << "n Sum of all Given Number" << sum;
    getch();
    }
    
  • 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

You must be logged in to post a comment.