Goto Statement In C Programming Language

Programming

goto statement – C supports a special type of a statement that is the Goto Statement that is used from one point to another to branch unconditionally within a program. While the use of the goto statement in C is not a good idea, there might be certain circumstances where it would be preferable to use the goto declaration.

The goto statement is used by programmers to modify a C program’s execution sequence by transferring the control to another section of the same program.

In C, the goto declaration is known as the jump statement. As the name suggests, goto is used to move a predefined label to the program power. For a specific situation, the goto status may be used to repeat any portion of the code. It can also be used by using a single break statement to break the different loops that can not be completed. However, because it makes the software less readable and complex, the use of goto is avoided these days.

An identifier is a label. When the goto statement is encountered, program control jumps to label: and the code begins to run.

We may use a goto statement to pass control of the software from down to top (↑) and top to down (↓).

Syntax:

Syntax1      |   Syntax2
----------------------------
goto label;  |    label:  
.            |    .
.            |    .
.            |    .
label:       |    goto label;

The first line tells the compiler in the above syntax to go to the statement marked as a label or to move to it. Here the label is an identifier specified by the user which indicates the target statement. After ‘label:’ the statement immediately followed is the destination statement. Even the ‘label:’ can appear before the ‘goto label;’ in the above syntax sentence.

A label is an identifier necessary for a goto declaration to a position where the branch is to be generated. A label is a valid variable name that is followed by a colon that is placed immediately before the statement where the control needs to be unconditionally jumped / transferred.

goto example:

Let’s see a clear example in the C language of using goto statement.

goto statement

Output:

Enter the number whose table you want to print : 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

When To Use Goto Statement In C Language

While using goto is almost always a bad programming technique (you can always find a better way to do XYZ), there are times when it’s not such a bad choice. Some may even argue that it is the best option if it is useful.

Most of what I have to say about goto only applies to C. If you are using C++ in place of exceptions, there is no sound justification to use goto. However, in C you don’t have the power of an exception handling system, so if you want to isolate error handling from the rest of your program logic, and you want to avoid multiple rewriting of clean up code in your code, then goto can be a good choice.