Home / Questions / What is the use of goto statement?
Explanatory Question

What is the use of goto statement?

👁 891 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

The goto statement in C language is used to transfer control unconditionally from one point in the program to another. It allows jumping to a labeled statement within the same function.

Syntax:


goto label;
...
label:
    // Statements to execute

Example:


#include <stdio.h>

int main() {
    int num = 5;

    if (num == 5) {
        goto skip;  // Jump to the label "skip"
    }

    printf("This line will be skipped.\n");

skip:
    printf("Jumped to the label using goto.\n");

    return 0;
}

When to Use goto:

  • When breaking out of deeply nested loops.
  • When handling error conditions to jump to a cleanup block.

When to Avoid goto:

  • It makes code hard to read and difficult to debug.
  • It can lead to spaghetti code, reducing maintainability.

Better Alternatives:

  • Use loops, functions, and conditional statements (if-else, switch-case) instead of goto for better structured programming.