Table of Contents
The goto statement transfers program control directly to a labeled statement within the same function. The destination is identified by a label followed by a colon (:).
Although goto can be used to create direct control-flow paths, excessive use can make program execution difficult to follow. Structured control statements such as if, loops, and switch are generally preferred for ordinary control flow.
Source Code #
#include <iostream>
int main()
{
int number = 5;
if (number > 0)
{
goto positive;
}
std::cout << "Number is not positive.\n";
return 0;
positive:
std::cout << "Number is positive.\n";
return 0;
}
Output #
Number is positive.
Explanation #
- The
gotostatement transfers control to a labeled statement. goto positive;transfers execution directly to the statement associated with thepositivelabel.- A label is an identifier followed by a colon, as in
positive:. - Labels have function scope, so a
gotostatement can transfer control only within the same function. - Because
number > 0evaluates totrue, thegotostatement is executed. - The statements between the
gotostatement and the target label are skipped. gotocan transfer control both forward and backward within a function, but excessive use can produce difficult-to-maintain control flow.- Structured constructs such as
if,else, loops, andswitchare generally preferred for normal program flow. return 0;terminates the program successfully.