How to use goto statement in C++
goto statement:
the goto statement just provides a jump , so that flow of program will shift from goto statement to label in the same function.Use of goto statement is highly discouraged , because it makes the program difficult , if the program is too long , then it becomes very difficult to judge the flow of program.
The advantage of goto statement is to exit from the nested loops.
Additional things like program code will extend if you eliminate the goto statement.
Difference between break and goto statement:
Break statement just cause the program to exit from the loop , in case of nested loops if you want to exit from the innermost loop to out of all the loop , then there goto statement works.
Syntax:
Syntax:
The syntax of goto statement in C++ is
goto label;
..
..
..
label: statement;
label: label is an identifier, it will identify the statement which is notified by the goto statement.label is followed by colon.
Lets take an example
Program code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int x = 0;
Loop:do
{
if(x == 5)
{
x = x + 1 ;
goto Loop;
}
cout<< " value of x "<< x <<endl;
x = x + 1;
} while(x < 10 );
getch();
}
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int x = 0;
Loop:do
{
if(x == 5)
{
x = x + 1 ;
goto Loop;
}
cout<< " value of x "<< x <<endl;
x = x + 1;
} while(x < 10 );
getch();
}
Click on image to enlarge it.
Output: When above program is executed , the output result is
Keep practicing on it.
any alternate statement of goto
ReplyDeleteNice
ReplyDelete