C++Builder Discover Goto and Labels in C++

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Discover Goto and Labels in C++
By Yilmaz Yoru April 14, 2021

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;
C++:
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,
C++:
mylabel:
   cout<< "this text comes after label\n";
Now, let’s see both together how they operate,
C++:
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,
C++:
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,
C++:
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.