✏️ Explanatory Question

What is the use of goto statement?

👁 891 Views
📘 Detailed Answer
No previous question
No next question
💡

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.
No previous question
No next question