The goto statement in C++ is a control flow statement that unconditionally transfers control to a specified label in the code. It is often referred to as a jump statement because it allows for jumping from one part of the code to another, bypassing the usual control flow mechanisms.
goto label; // Unconditionally jumps to the specified label
K
// Code block...
label: // This is the label to which control jumps
// Code block...
• Labels: A label is an identifier followed by a colon (:) that marks a location in the code. It is used as the target for the goto statement.
• Control Transfer: When goto is used, the program's execution jumps directly to the labeled statement, skipping any code in between.
• Usage: The goto statement is rarely used in modern C++ programming due to its potential to create hard-to-follow code. It is often replaced with structured control flow mechanisms like loops and functions.
#include <iostream>
using namespace std;
int main() {
int i = 0;
start: // Label
if (i < 5) {
cout << "i = " << i << endl;
i++;
goto start; // Jump to the start label
}
return 0;
}
i = 0
i = 1
i = 2
i = 3
i = 4
In this example, the goto statement jumps back to the start label as long as i is less than 5, resulting in a loop-like behavior.
• Direct Jump: Allows for direct jumps to any part of the code with the specified label.
• Control Transfer: Useful for transferring control in cases where other control flow statements would be less efficient or less clear.
• Readability: Overuse of goto can make code harder to read and maintain, leading to "spaghetti code" where the flow of control is unclear.
• Structured Programming: Modern C++ programming favors structured control flow constructs like loops and functions, which provide clearer and more maintainable code.
• Scope Issues: Labels must be within the same function or block scope as the goto statement.
The goto statement can be used to escape from deeply nested loops or switch statements, but this should be done with caution:
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (j == 2) {
goto
end; // Jump to the end label
}
cout << "i = "
<< i << ", j = " << j << endl;
}
}
end: // Label
cout << "Exited from nested loops" << endl;
return 0;
}
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Exited from nested loops