Quick links: HR Interview Que. Code Snippets C Programs C++ Programs Java Programs Scala Solved Examples PHP Examples

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;

Sponsored Links

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 !!!

COMMENTS

Keywords (like Linux, Java, Oracle etc) used in this website are the trademarks of their respective owners/company. This website is not affiliated to any company. The tutorials are designed by includehelp Team with the help of well known books and other online resources. These Tutorials are free for all, for learning purposes only. Enjoy learning:)
Copyright © 2015 - 2016. All Rights Reserved.