c++language-agnosticgoto

goto statement in language standard


Most people nowadays don't use goto statement in their code. Good. In SO there are many threads on goto usage, all of them "allowing" it for exiting deep loops.

To show a few:

GOTO still considered harmful?

What is wrong with using goto?

Are there any legitimate use-cases for "goto" in a language that supports loops and functions?

Examples of good gotos in C or C++

I looked at cppreference.com, which tells:

Used when it is otherwise impossible to transfer control to the desired location using other statements.

What rings my bells is "otherwise impossible"

Can any body show examples where goto can't be avoided?

Note: I've tagged this question as "C++", just because I'm more interested in C++ samples. Any other language is good for me.


Solution

  • First of all, it's been proven (like a mathematical proof) that anything you can do with goto's, you can also do without them. But in some cases, you end up with duplicated code, or more complex control structures.

    But the sentence in question only talks about transferring control to a place that you couldn't with other control structures. The primary example of this would be transferring control into the body of a loop. For example, consider the fairly common requirement to print out some numbers (or strings, etc.) separated by commas, so we have commas between the items, but not before the first or after the last. One way to do this is something like this:

    goto start;
    while (i < n) {
        print(',');
    start:
        print(input[i++]);
    }
    

    The only way to transfer control directly into the middle of the loop body like this is a goto. The sole alternative is to simply not transfer control into the middle of the loop body at all. And you can certainly do that:

    bool first = true;
    while (i < n) {
        if (!first) {
            print(',');
        }
        first = false;
        print(input[i++]);
    }
    

    Of course there are other possibilities as well. But for the specific requirement of transferring control into the middle of the loop body, goto is the only thing that works.