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, it may make more sense and be more readable to use a goto to jump to clean up code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset