Use of goto statement in C programming

The goto is an unconditional jump statement that transfers the control to a label (identifier). The label must reside in the same function and at least one statement appears after the label.

Syntax:

goto label;
label:
statement;

 

Note: goto can jump forward and backward both.

It is good to use a break, continue and return statement in place of goto whenever possible. It is hard to understand and modify the code in which goto has been used. So you should avoid the use of goto statement in the program. Sometimes goto statement useful to handle the code exception and break the nested loop but still, you should avoid it as possible.

Flow Diagram of goto statement in C

 

goto in c

 

Example,

In below example, I am skipping the statement2 with the help of goto jump statement.

#include <stdio.h>

int main(void)
{

    printf(" Statement 1\n\n");

    goto Label3;

    printf(" Statement 2\n\n");

Label3:
    printf(" Statement 3\n\n");

    printf(" Statement 4\n\n");

    return 0;
}

Output:

goto in c

 

Some important point related to goto statement in C

1. There should be one statement after the label. If there is no statement occur after the label, then you will get the compiler error. See the below example,

Error: label at end of compound statement

Above code will compile if we write any single statement or put a semicolon ( ; ) after the label.

#include <stdio.h>

int main(void)
{

    printf(" Statement 1\n\n");

    goto Label3;

    printf(" Statement 2\n\n");

Label3:
    ;

}

Output: Statement 1

 

2. According to C standard, “A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier“.

Example 1,

#include <stdio.h>

int main(void)
{
    int n = 9;

    goto Label;
    {
        int a[n];
Label:
        printf("Hello aticleworld\n");
    }

    return 0;
}

Output:

goto jump

Example 2,

#include <stdio.h>

int main(void)
{
    int n = 9;

    {
        printf("Hello \n");
        int a[n];
Label:
        printf("aticleworld\n");
    }
    goto Label;

    return 0;
}

Output:

goto jump

3. In C, a label must follow the statements. So if you write a declaration just after the label, you will get a compiler error.

#include <stdio.h>

int main(void)
{

    goto Label;

Label:
    int a =7;

    return 0;
}

Output:

[Error] a label can only be part of a statement and a declaration is not a statement.

 

If you want to declare a variable after the label, then you have to write a statement or an empty statement ( ; ) after the label. In below example, I am inserting an empty statement after the label.

#include <stdio.h>

int main(void)
{
    goto Label;

Label:
    ;
    int a =7;

    return 0;
}

 

Recommended Articles for you: