Understanding of goto Statement in C Language

The C programming language offers a somewhat infamous feature known as the “goto” statement, often ref

erred to as a jump statement. As its name implies, “goto” is used to transfer program control to a predefined label within the code. While “goto” can be employed to repeat a portion of code based on a specific condition or to break out of multiple nested loops efficiently, it is generally discouraged in modern programming practices due to its potential to make code less readable and more complex.

Syntax:

The basic syntax for using the “goto” statement in C is as follows:

label:
// Some part of the code;
goto label;

Here is an example of the “goto” statement in action:

#include <stdio.h>
int main()
{
  int num, i = 1;
  printf("Enter the number whose table you want to print?");
  scanf("%d", &num);
table:
  printf("%d x %d = %d\n", num, i, num * i);
  i++;
  if (i <= 10)
    goto table;
}

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 Should We Use “goto”?

The use of the “goto” statement is generally discouraged, and modern programming practices aim to minimize its use. However, there are certain scenarios where it can be considered:

Breaking Out of Nested Loops: “goto” can be useful when you need to exit multiple nested loops simultaneously, which is challenging to achieve with a single “break” statement. For instance:

#include <stdio.h>
int main()
{
  int i, j, k;
  for (i = 0; i < 10; i++)
  {
    for (j = 0; j < 5; j++)
    {
      for (k = 0; k < 3; k++)
      {
        printf("%d %d %d\n", i, j, k);
        if (j == 3)
        {
          goto out;
        }
      }
    }
  }
out:
  printf("Came out of the loop");
}

Output:

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
Came out of the loop

In this example, the “goto” statement helps exit the nested loops when j equals 3.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading