goto
The
goto statement allows jumping
to a statement contained within the same
function. The target statement must be preceded by a label:
goto outOfLoop;
// statements
outOfLoop: cout << "Sum of indices is 5";
The use of
goto should be limited to cases
in which it greatly contributes
to code readability or efficiency, as its use is never strictly necessary
and somewhat conflicts with the need to maintain consistency between
the order of statement execution and the one in which statements
are written.
See the following example in which a
goto
is used to exit four nested loops. The alternative would be to execute four
different
break statements, one for each
loop.
Example
#include <iostream>
using namespace std;
int main()
{
for(int i = 0; i <= 3; i++)
for(int j = 0; j <= 3; j++)
for(int k = 0; k <= 3; k++)
for(int l = 0; l <= 3; l++)
{
cout << i << " " << j << " " << k << " " << l << "\n";
if(i + j + k + l == 5) // stop when sum of indices is 5
goto outOfLoop; // if I didn't have this I would have to have three more if(...) break;
}
outOfLoop: cout << "Sum of indices is 5";
}
Output
0 0 0 0
0 0 0 1
0 0 0 2
0 0 0 3
0 0 1 0
0 0 1 1
0 0 1 2
0 0 1 3
0 0 2 0
0 0 2 1
0 0 2 2
0 0 2 3
Sum of indices is 5