C goto Statement – Complete Guide with Examples

The goto statement in C is used to jump to a labeled part of the program. It can transfer control anywhere within the same function, regardless of the normal flow of execution.

 Use goto with caution—it can make code harder to read and maintain.

Syntax of goto in C

 

goto label;

// … other code …

label:
// code to execute

Example: Basic goto Usage

#include <stdio.h>

int main() {
    int num = 3;

    if (num == 3) {
        goto skip;
    }

    printf("This line is skipped.\n");

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

    return 0;
}

 Output:

Jumped to the label 'skip'.

Example: Using goto to Exit Nested Loops

#include <stdio.h>

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

exit_loops:
    printf("Exited both loops using goto.\n");

    return 0;
}

 Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Exited both loops using goto.

When to Use goto (Rarely)

 Use Case Why
Exiting multiple nested loopsCleaner than using multiple flags
Jumping to error handling sectionUsed in some legacy C systems

When NOT to Use goto

Poor Practice Reason
Jumping across large code blocksReduces readability
Skipping initialization or cleanupMay lead to bugs or memory leaks
Overusing in modern codeBetter alternatives exist (loops, functions)

Best Practices

PracticeReason
Use meaningful label namesImproves clarity
Minimize goto usageMakes the code cleaner and structured
Replace goto with loops/functionsEncourages structured programming

Read More

How to Create Database in MySQL

  • By admin
  • November 27, 2021
  • 65 views
How to Create Database in MySQL

How to create table in MySQL

  • By admin
  • November 6, 2021
  • 46 views
How to create table in MySQL

MySQL commands with examples

  • By admin
  • September 11, 2021
  • 139 views
MySQL commands with examples

MySQL use database

  • By admin
  • May 28, 2021
  • 45 views
MySQL use database

System Software

  • By admin
  • May 20, 2021
  • 66 views

Introduction to software

  • By admin
  • May 13, 2021
  • 58 views
Introduction to software