example of goto statement in c

Goto statement in  C 

In this Tutorial,You will learn what is the use of  goto statement in c programming.You will also learn when we should use goto statement,when we should not,advantage and disadvantage of goto statement.

The goto statement in C/C++ is used to jump to a particular label hence we can say that goto statement is a brancing statement which is jump from one statement to another.The goto is keyword in c so  we can't use goto as a identifiers in our program.

Labels:The labels in goto statement are nothing but an identifier.If you don't known what is identifier then click here.The use of Label in goto statement is when the goto statement is encountered,the control of the program jumps to label and starts executing the further code.

Syntax for goto statement

Example for goto statement 
#include <stdio.h>

int main() {
printf("Hello World\n");
goto E;
printf("Good Morning");
E:
printf("Good Night");
return 0;
}

Output:

Hello World
Good Night

In above example,when the execution will start first  hello world  will be printed after that we are using goto statement so the control will directly jump to E label and statement between them will be skipped and the statements after that label will be normally executed.

In above eg,we have taken very simple program because this tutorial is mainly designed for beginners.

Reasons to avoid goto

When we use goto statement it may lead to code that contains bugs and hard to follow Let's understand with an example 

one:
for (i = 0; i < number; ++i)
{
    test += i;
    goto two;
}
two: 
if (test > 5) {
  goto three;
}
... .. ...

Also, the goto statement allows you to do bad stuff such as jump out of the scope.

That being said,goto can be useful sometimes. For example: to break from nested loops.

Should you use goto?

If you think that the utilization of goto statement simplifies your program, you'll use it. That being said, goto is never useful and you'll create any C program without using goto altogether.

Here's a quote from Bjarne Stroustrup, creator of C++, "The incontrovertible fact that 'goto' can do anything is strictly why we do not use it."

Advantage of using goto statement:

using goto statement you'll alter the traditional sequence of the program execution so it gives the facility to leap to any a part of program.

 Disadvantages of using goto statement:

  • the utilization of goto statement is very discouraged because it makes the program logic very complex.
  •  use of goto makes the task of analyzing and verifying the correctness of programs (particularly those involving loops) very difficult.
  •  Use of goto are often simply avoided using break and continue statements.
If you any have doubt,suggestion regarding this post or website then feel free to share with us.
 
If you have learned something new from this post then share this post with your family and
friends.
 
Happy Learning :)😎  

2 Comments

Previous Post Next Post