Site icon Learn C++

Discover Goto and Labels in C++

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;

[crayon-6606cf2ccf3b5028895124/]

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,

[crayon-6606cf2ccf3bb113126913/]

Now, let’s see both together how they operate,

[crayon-6606cf2ccf3bd762037351/]

here first text will not be displayed. We can use goto to exit from for() loops,

[crayon-6606cf2ccf3bf153462914/]

we can use goto to exit from while() or do-while() loops,

[crayon-6606cf2ccf3c0819236924/]

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!

Exit mobile version