goto statement
The goto statement can make the program jump to any statement marked with a label (Label).
goto statement
#include <iostream>
using namespace std;
//goto语句
int main()
{
goto here ;
cout << "本应该输出这句。" << endl;
here:
cout << "现在打印这句。" << endl;
return 0;
}
Running result:
the first output statement in the example is skipped, the program directly jumps to here through goto, and only the second output statement is printed.
Try again the example of implementing a while loop with two goto statements
While loop using goto statement
#include <iostream>
using namespace std;
//使用goto语句实现while循环
int main()
{
int i =0;
loophead:
if ( i >= 10 )
goto loopend;
cout << i << endl;
i++;
goto loophead;
loopend:
return 0;
}
The result:
This example behaves almost exactly like a while loop, but looks a lot harder to read. loophead marks the beginning of the loop, if the counter i is greater than or equal to 10, then the loop ends, goto will jump to loopend which marks the end of the loop; if the counter is less than 10, the loop will proceed normally, and will automatically jump to loophead at the end .
If it is helpful to you, please like and support it~