In C Language, the goto statement is used to transfer control to a labelled statement within the same function.
It is often considered harmful and can make code difficult to read and understand if misused.
However, in certain situations, it can be useful for implementing specific control flows.
Unconditional Jump: The "goto" statement allows us to transfer control to a specific label within the same function unconditionally when it met.
Labeled Statements: we can define labels within code followed by a colon `:`, and then we define `labels` with the "goto" statement to transfer control.
Limited Use: It can make the code difficult to read, debug and maintain.
Jump to Any Location: The "goto" statement allows us to jump to any labeled statement within the same function, including outside of nested loops and conditionals.
Potential for Error: Improper use of "goto" can lead to infinite loops, unreachable code, and other logic issues.
Here's the syntax of the goto statement in C Language:
goto label;
Where "label" is an identifier followed by a colon ":" placed before a statement.
#include <stdio.h> int main() { int i = 0; loop: // label if (i < 5) { printf("%d ", i); i++; goto loop; // jump to label } return 0; }
0 1 2 3 4
#include <stdio.h> int main() { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (i == 2 && j == 2) { goto endloop; // Exit both loops when i is 2 and j is 2 } printf("(%d,%d) ", i, j); } } endloop: printf("\nLoop End and Priniting from goto keyword"); return 0; }
(0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) Loop End and Priniting from goto keyword
#include <stdio.h> int main() { int option = 1; switch (option) { case 1: printf("Option 1\n"); // No Break Keyword added because of it remove to case 2 case 2: printf("Option 2\n"); goto endswitch; // Skip the remaining switch cases case 3: printf("Option 3\n"); break; default: printf("Invalid option\n"); break; } endswitch: printf("Switch ended\n"); return 0; }
Option 1 Option 2 Switch ended
These examples illustrate various uses of the goto statement. However, it's important to note that excessive use of goto can lead to code that is difficult to understand and maintain.
In most cases, structured programming constructs such as loops and conditional statements are preferred.