The goto statement in c++

             
We have gone through the while loop, for loop and do-while loop. The another way to do loop in c++ is through using the goto statement. The goto statement was used in olden days but it is not suitable for creating modern applications. But since c++ supports it, you should have knowledge about it, as you may encounter a c++ source code containing goto statements, in that case you will know what it is and how it works.
It consist of label and statements that comes under that label. A label is named by you and it is followed by a colon sign (:). During execution of program, when goto is encountered, it jumps to the statements that comes under the label specified by goto statement. To get a clear idea, analyze the below program example.
/* A c++  example that uses goto statement to display number from 0 to 9

#include <iostream>
using namespace std;
int main ()
{
    int i=0;
loop:
    cout << i << endl;
i++;
if (i<10)
goto loop;
return 0;
}
Why goto should not be used?

The use of goto should be avoided to make the program more readable and reliable. The goto statement can cause the program execution to jump to any location in source code and in any direction backward or forward. This makes the program hard to read and understand and also makes it difficult to find bugs.
Since now we have more tightly controlled and sophisticated loops like while loop, for loop and do-while loop, the use of obsolete statement like goto is not at all recommended in creating loops.
The goto statement in c++
How the goto statement works?
*/

Post a Comment

0 Comments