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


Avoid use of goto statements unless necessary

5.5 -- While statements
5.3 -- Switch statements

74 comments to 5.4 — Goto statements

  • kk

    isn't switch statement faster then if-else when number of cases are more than 5?

    • nascardriver

      `switch` statements should never be slower than `if` statements. They can start being faster than a linear `if` at 4 cases (As far as I can tell).

      To get to the maximum depth (d), we need 3 comparisons. The average cost is 9/4 (9 is the sum of comparisons, 4 is the number of cases).

      To get to the maximum depth (d), we need 2 comparisons. The average cost is 8/4=2 plus the goto.
      If this `switch` is faster than the `if` depends on the speed of the `goto`. If the compiler knows that the `goto` is too slow, it can always fall back to a linear check.

  • Christian

    Is this lesson broken or just me? Anyone else?

  • Jiana

    >The goto statement and its corresponding statement label must appear in the same function.

    Would you please give an example that violates the rule of the sentence above?

    Q2: In the code below, I initialized the variable 'w' within the function scope of go-to statement, but I still was able to print its value after the function scope finishes.why? it is confusing!

  • Alek

    hello,in the context above you say :you can’t jump forward over a variable that’s initialized in the same block as the goto.I tried to leave it uninitialized and it works fine! I wonder if you can tell me why can't it jump over an initialized variable ? what is the reason?
    2: I read @bronzdragon answer to SM.Haider he says:Statement labels aren't actually variables, so they're not allocated the same how are they allocated ? how many different allocation do we have in c++ are there any websites that can extend this topic and talk about these in details?
    thanks in advance!

    • nascardriver

      If a variable has an initializer, we're safe to assume that the variable is initialized when we first use it. Jumping over the initialization would violate this, as the variable would be declared, but not initialized (Initialization occurs when control passed through the definition, but if you just over the definition, control never passes through it).

      Statement labels are not objects, they don't take up any memory, they don't get allocated.

  • Nathuunn

    what if I created a calculator and wanted to repeat the whole thing over again so i can solve another problem what should I do then?

  • Raffaello

    "Rule: Avoid use of goto statements unless necessary"
    I'm curious now, when a goto statement would be necessary? (also, shouldn't that be in a red box?)

    • nascardriver

      It's never really necessary. It can be handy for breaking out of nested loops, but even that can be done without `goto`.

  • SM.Haider

    I have a question or two;
    Once you initialize a variable, (obviously) it allocates a specific quantity of memory, so how many bytes of memory does a statement label allocate?
    Secondly, if we utilised numerous goto statements in a program, will that delay the performance of the processor?

    • Bronzdragon

      Statement labels aren't actually variables, so they're not allocated the same way.

      To keep it simple, when the compiler compiles your code, it converts your programme to byte code. Each statement translates to 1 or more instructions (or sometimes zero, due to optimization). Each instruction has a position in the code. When you create a statement label, the compiler remembers the offset to the next instruction. When you jump, it takes the address of the start of your programme, and the offset, and jumps there.

      This offset is stored directly in the instruction, it's not in any way dynamic, like variable decelerations are normally.

    • June

      Hmm to put it another way, I think the best analogy is a bookmark. To keep things simple, when you compile your program it places a bookmark next to the code beneath it. This is all the label amounts to. It doesn't make your program any bigger or smaller and doesn't take up any memory. It's just a simple bookmark that the compiler uses so that it knows where exactly to make the program jump to. Theres a lot more but I'm keeping things very simple.

      Jumping around is very crucial to some languages, notably one of my favorites, assembly. However that's not really the way of C++ outside very special cases you won't hardly encounter. If you feel like a goto statement would work well then it's usually the case to sit back a minute and rethink your program so far. Of course you can always play around with goto to delve a bit into curiosity just know that in normal C++ programs it's not really expected to be used.

      I hope I answered your question well ^_^

Leave a Comment

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