goto statement in C and C++

The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used to jump from anywhere in general conditions.

NOTE − the use of goto statements in any programming language is strongly discouraged because it makes it difficult to track a program’s control flow, making it very difficult to understand the program and difficult to modify. 

Syntax:

The first line in the syntax above tells the compiler to go, or jump to, the statement marked as a label. The label here is a user-defined identifier indicating the target declaration. The statement followed immediately after ‘label:’ is the state of destination. In the above syntax, the ‘label:’ may also appear before the ‘goto label;’ statement.

goto statement in C and C++

Example:

1. We shall see a similar situation in this case to the one shown above in Syntax1. Assume we have to write a program where we have to check whether there is a number even or not and use the goto statement to print consequently.The program below explains how:

Output:

goto statement in C and C++

Example in C:-

Output:

goto statement in C and C++

2. In this case, we can see a similar situation to the one seen in Syntax1 above. Suppose we have to write a program using the goto statement, which prints numbers from 1 to 10. The program below explains how to do so.

Output:

goto statement in C and C++

Example in C:

Output:

goto statement in C and C++

Disadvantages of using goto Statement:

The use of the goto statement is highly disincentive as it makes the logic of the program very complex.

The use of goto makes it very difficult to evaluate and verify the correctness of the programs (especially those that require loops).

Using break and continue statements can simply avoid the use of goto.

Pin It on Pinterest

Share This