0
0
Cprogramming~5 mins

Goto statement overview in C

Choose your learning style9 modes available
Introduction

The goto statement lets you jump to another part of your program quickly. It helps you skip or repeat code without using loops or functions.

To exit deeply nested loops or conditions early.
To handle errors by jumping to a cleanup section.
To avoid repeating code by jumping to a shared code block.
When you want simple control flow without complex structures.
Syntax
C
goto label;
...
label:
    // code to execute

The label is a name followed by a colon.

You can jump only within the same function using goto.

Examples
This jumps to the label end and prints a message.
C
goto end;
...
end:
    printf("Jumped here!\n");
Jump to error label if a condition is true.
C
if (x < 0) {
    goto error;
}
...
error:
    printf("Error found!\n");
Sample Program

This program uses goto to create a loop that prints numbers from 0 to 2, then jumps to end to finish.

C
#include <stdio.h>

int main() {
    int i = 0;

start:
    if (i >= 3) {
        goto end;
    }
    printf("i = %d\n", i);
    i++;
    goto start;

end:
    printf("Loop ended.\n");
    return 0;
}
OutputSuccess
Important Notes

Use goto carefully because it can make code hard to read.

Modern code usually prefers loops and functions instead of goto.

Summary

goto jumps to a labeled part of the code inside the same function.

It can simplify some tasks like breaking out of nested loops or error handling.

Use it sparingly to keep code clear and easy to understand.