The goto statement is used to jump to a label that provides an unconditional jump from the goto to a labeled statement in the same function. We can also do the same loops as the same in for() while() loops by using goto statement. Instead of goto we mostly use for(), while(), do-while() statements or functions, classes, because they are faster and better than using goto. Rarely sometimes we need to use goto to pass some lines or to jump to other lines in a function or the main program. goto statement can be only used with a label as below;
1 2 3 |
goto mylabel; |
to use this, we must also define mylabel there. label is an identifier that identifies a labeled line or statement and a labeled statement is a statement that is preceded by an identifier followed by a colon ‘:’ character, labels are alpahnumeric texts without spaces, for example we can define mylabel like this,
1 2 3 4 |
mylabel: cout<< "this text comes after label\n"; |
Now, let’s see both together how they operate,
1 2 3 4 5 6 7 |
goto mylabel; std:cout << "you can NOT see this text"; mylabel: std:cout << "you can see this text"; |
here first text will not be displayed. We can use goto to exit from for() loops,
1 2 3 4 5 6 7 8 9 10 |
for( int a=0; a<=10; a++) { std::cout << a << ","; if(a>=5) goto mylabel; } mylabel: std::cout << "done\n"; |
we can use goto to exit from while() or do-while() loops,
1 2 3 4 5 6 7 8 9 10 11 |
int a=0; while ( a<10 ) { a++; if( a>=5 ) goto mylabel; } mylabel: std::cout << "done\n"; |
We can NOT use goto to jump to other label of a function. it only works inside functions. For example you can not jump from main to a label in a sub-function.
Get started building powerful apps with C++Builder!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition