C Goto

🚀 C Goto Statement – Jump Control in C

The goto statement in C allows you to jump to a labeled part of the program. While it’s powerful, it’s generally avoided because it can make code harder to understand. Still, it’s useful in some rare cases, like exiting deeply nested loops or handling errors.

🔹 Syntax of goto

goto label_name;
// ...
label_name: statement;

📝 Example 1: Basic goto Usage

Here’s a simple example where we jump directly to a label.

#include <stdio.h>

int main() {
    printf("Before the jump\n");
    goto jump_here;
    printf("This line is skipped\n");

    jump_here:
    printf("Landed using goto!\n");
    return 0;
}
  

Try It Now

📝 Example 2: Using goto to Exit Nested Loops

This shows how goto can break out of multiple loops.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (i * j == 4) {
                goto end_loops;
            }
            printf("i=%d, j=%d\n", i, j);
        }
    }

    end_loops:
    printf("Exited nested loops using goto\n");
    return 0;
}
  

Try It Now

⚠️ When to Avoid Goto

  • Can make code confusing and hard to debug.
  • Better alternatives often exist (like functions, break, continue).

✅ When It’s OK to Use

  • Error handling in low-level programming.
  • Exiting deeply nested loops quickly.

💡 Practice Time!

Try creating a program that uses goto to jump between different tasks like printing menus or skipping sections. But use it wisely — like hot sauce, a little goes a long way!