Jumping

C++ supports jumps, and in most cases, there are better ways to branch code; however, for completeness, we will cover the mechanism here. There are two parts to a jump: a labeled statement to jump to and the goto statement. A label has the same naming rules as a variable; it is declared suffixed with a colon, and it must be before a statement. The goto statement is called using the label's name:

    int main()     {         for (int i = 0; i < 10; ++i)         {             std::cout << i << std::endl;             if (i == 5) goto end;         }         end:        std::cout << "end";     }

The label must be in the same function as the calling goto.

Jumps are rarely used, because they encourage you to write non-structured code. However, if you have a routine with highly nested loops or if statements, ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.