c
  1. c-goto-statement

C goto Statement

Syntax

goto label;

// code to be skipped
:
// code to be executed after the goto statement

label: 
// code to be executed after the goto statement reaches the label

Example

#include <stdio.h>

int main() {

  int num = 0;

  loop: // label
  
  printf("%d\n", num);
  num++;

  if(num < 10) {
    goto loop; // goto statement
  }

  return 0;
}

Output

0
1
2
3
4
5
6
7
8
9

Explanation

The goto statement in C is used to transfer control to another part of the program. It is often used to jump out of nested loops, or to implement error handling. The goto statement uses a label to indicate the target of the jump.

Use

The goto statement is generally discouraged in modern programming languages because it can make the code difficult to read and understand. However, it can be useful in certain situations, such as breaking out of multiple nested loops or implementing error handling. The goto statement should be used sparingly and only when there is no other reasonable alternative.

Important Points

  • The use of goto statements can make the code harder to understand and maintain, and can make it more difficult to find and fix bugs.
  • The goto statement can only be used to transfer control within a function. It cannot be used to transfer control between functions.
  • The goto statement should be used sparingly and only when there is no other reasonable alternative.

Summary

The goto statement in C is a powerful tool for transferring control within a program. It can be useful in certain situations, such as breaking out of nested loops or implementing error handling. However, the use of goto statements can make the code harder to understand and maintain, and can make it more difficult to find and fix bugs. It should be used sparingly and only when there is no other reasonable alternative.

Published on: