×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

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

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.