C++ goto statement
Created By: chatGPT
The
In this example, a variable goto
statement in C++ is used to jump to a specified label within a function. While it provides a way to transfer control, its use is generally discouraged because it can lead to spaghetti code—code that is unstructured and hard to follow. However, there are legitimate scenarios where goto
can be useful for simplicity, such as breaking out of deeply nested loops or handling cleanup operations. Here's an example demonstrating how to use the goto
statement:#include <iostream>
int main() {
int a = 0;
start:
std::cout << "Value of a: " << a << std::endl;
a++;
if (a < 5) {
goto start; // Jump back to the 'start' label
}
std::cout << "Finished!" << std::endl;
return 0;
}
a
is initialized to 0, and a label called start
is defined. The program prints the value of a
, increments it by 1, and uses the goto
statement to jump back to the label as long as a
is less than 5. Once a
reaches 5, the loop terminates, and the program outputs 'Finished!'. When you compile and run this code, you will see how the goto
effectively manages the control flow in this case, but be aware of potential readability issues when using it in larger programs.