Home » C programming language

'goto' Statement in C language



goto is a jumping statement in c language, which transfer the program’s control from one statement to another statement (where label is defined).

goto can transfer the program’s within the same block and there must a label, where you want to transfer program’s control.

Defining a label

Label is defined following by the given syntax

label_name:
  • label_name should be a valid identifier name.
  • : (colon) should be used after the label_name.

Transferring the control using ‘goto’

Program’s control can be transfer following by the given syntax

goto label_name;

Two styles of ‘goto’ statement

We can use goto statement to transfer program’s control from down to top (↑) and top to down (↓).

Style 1 (Transferring the control from down to top)

// style 1
label-name:
    statement1;
    statement2;
    ..
    if(any-test-condition)
        goto label-name;

Here, if any-test-condition is true, goto will transfer the program’s control to the specified label-name.

Consider the following example/program

/*To print numbers from 1 to 10 using goto statement*/
#include <stdio.h>
int main()
{
    int number;
    number=1;
 
repeat:
    printf("%d\n",number);
    number++;
 
    if(number<=10)
        goto repeat;
 
    return 0;
}

Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

Style 2 (Transferring the control from top to down)

// style 2
statements;
    if(any-test-condition)
        goto label-name;
    statement1;
    statement2;
    label-name:
        Other statements;

Here, if any-test-condition is true, goto will transfer the program’s control to the specified label-name.

Consider the following example/program

/* To read and print the number, if number is positive only*/
#include <stdio.h>
int main()
{
    int number;
 
    printf("Enter an integer number: ");
    scanf("%d",&number);
 
    if(number<=0)
        goto end;
    printf("Number is : %d", number);
 
end:    
    printf("Bye Bye !!!");
    return 0;
}

Output

    First run:
    Enter an integer number: 123
    Number is : 123
    Bye Bye !!!

    Second run:
    Enter an integer number: 0
    Bye Bye !!!





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.