goto Statement

0 zoilamckee65622 November 13, 2020

The gotostatement is used to alter the normal sequence of program executing by unconditionally transferring control to some part of the program. The gotostatement transfers the control to some part of the program. The gotostatement transfers the control to the labeled statement somewhere in the current function. The gotostatement has the following form

goto label;

Here, the labelis an identifier used to label the target statement to which the control would be transferred. The target statement must be labeled using the syntax:

label: statement;

Generally, the use of a gotostatement is avoided as it makes the program illegible. This statement is used in unique situations like

  • Branching around statements or groups of statements under certain conditions.
  • Jumping to the end of a loop under certain conditions, thus bypassing the remainder of the loop during the current pass.
  • Jumping completely out of the loop under certain conditions, terminating the execution of the loop.

Let’s look at one example to make clear concepts on the goto statement.

#include <iostream>
using namespace std;

int main(){

    int i, num1, num2;

    cout << "Enter First Number" << endl;
    cin >> num1;

    if(num1 < 0)
        goto negative;

    cout << "Enter Second Number" << endl;
    cin >> num2;

    if(num2 < 0)
        goto negative;

    cout << "Both number are positive" << endl;
    return 0;

        cout << "Either Number is negative" << endl;

The output of the above program is:

a)  Enter First Number
     Enter Second Number
     Both number are positive

b)  Enter First Number
     Either Number is negative

c)  Enter First Number
     Enter Second Number
     Either Number is negative