• Home
  • 4.8 goto Statement

4.8 goto Statement

View Categories

4.8 goto Statement

1 min read

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 goto statement transfers control to a labeled statement.
  • goto positive; transfers execution directly to the statement associated with the positive label.
  • A label is an identifier followed by a colon, as in positive:.
  • Labels have function scope, so a goto statement can transfer control only within the same function.
  • Because number > 0 evaluates to true, the goto statement is executed.
  • The statements between the goto statement and the target label are skipped.
  • goto can 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, and switch are generally preferred for normal program flow.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *