Goto statement in C

Now we will see how goto statement is used?

As the name indicates, goto statement is used to jump from one place of code to another. It is like linking a code to another. When the compiler sees the goto statement, then the corresponding ‘Label’ code will executed next. 

Syntax of goto statement in C

goto label_name;
..
..
label_name: C-statements

Flow Diagram

C goto statement

Example of goto statement

#include<stdio.h>
int main()
{
   int sum=0;
   for(int i = 0; i<=10; i++)
{
 sum = sum+i;
 if(i==5){
    goto addition;
 }
   }

   addition:
   printf("%d", sum);

   return 0;
}

Output:

15

Explanation: In this example, we have a label addition and when the value of i (inside loop) is equal to 5 then we are jumping to this label using goto. This is reason the sum is displaying the sum of numbers till 5 even though the loop is set to run from 0 to 10.

Goto statement is not popular and not widely used.

Goto is mainly used for menu driven programs.

Leave a comment

Design a site like this with WordPress.com
Get started