C++ goto statement

goto statement is used for unconditional transfer of control anywhere in program. It is normally used with selection structure ( if statement ). goto statement is always used with predefined label. Label is the point where goto statement transfer control.


label :

   goto label;

Label may be any valid identifier name such as name of variable. colon is used after label.


#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	int a = 1;
	doAgain: // This is label.
		if( a<=5 ) {
			a = a + 1;
			goto doAgain; // here is goto statement is used.
	return 0;

The above code example will print counting from 1 to 10. Hence it does not use any iterative structure such as while, do while or for loop. But with the help of goto statement we can repeat the same task.

Login to TRACK of Comments.