goto Statement

0 verla19m6920035 November 25, 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 <stdio.h>

int main(){

    int i, num1, num2;

    printf("Enter First Number\n");
    scanf("%d", &num1);

    if(num1 < 0)
        goto negative;

    printf("Enter Second Number\n");
    scanf("%d", &num1);

    if(num2 < 0)
        goto negative;

    printf("Both number are positive\n");
    return 0;

        printf("Either Number is negative\n");

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