goto statement in C

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.

 

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.

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,

goto jump

Example 2,

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.

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.