Goto Statement in C
The goto statement in C allows unconditional transfer of control to a labeled statement within the same function. It is generally used to jump to a specific part of the code.
Syntax
label: statement; ... goto label;
Example
int i = 1; if (i == 1) { goto skip; } printf("This will be skipped\n"); skip: printf("Control jumped here\n"); // Output: Control jumped here
How It Works
- The goto statement transfers control to the labeled statement immediately.
- The label must exist within the same function; you cannot jump to a label in another function.
- It can be used inside loops or conditional statements to jump to a specific point.
- Overuse of goto can make code hard to read and debug.
Tips
- Use goto sparingly; prefer structured control statements like loops and if-else.
- Label names should be descriptive to indicate the purpose of the jump.
- Use goto for error handling in deeply nested conditions when necessary.
- Avoid jumping into loops or skipping variable initializations.
Common Mistakes
- Using goto excessively, which creates spaghetti code.
- Jumping to labels outside the current function, which causes a compile-time error.
- Skipping initialization of variables by jumping over declarations.
- Confusing goto with break or continue; they have different purposes.
Codecrown