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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.