Goto Statement
The goto
statement is a jump statement which jumps from one point to another point within a function.
The syntax of the goto
statement in C++ is:
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
In the syntax above, label
is an identifier. When goto label;
is encountered, the control of program jumps to label:
and executes the code below it.
Example:
num = 10
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd; even:
cout << num << " is even";
// return if even
return;
odd:
cout << num << " is odd";
You can write any C++ program without the use of goto
statement and is generally considered a good idea not to use them.
Reason to Avoid goto Statement
The goto statement gives power to jump to any part of program but, makes the logic of the program complex and tangled.
In modern programming, goto statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C++ program with the use of break
and continue
statements.