What are C Goto Rules and Pitfalls- C Programming Course With Examples

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Control Statements

C Goto Rules and Pitfalls

Learn the label rules, compiler errors and spaghetti-code risks of goto in C programming, plus the one embedded cleanup pattern where goto is genuinely useful.

Knowing how to write a jump is easy. Knowing when goto in C programming is safe is what separates a careful firmware engineer from a careless one. This lecture of our free C programming course lists the rules the compiler enforces, shows the exact error messages you will meet, explains why goto earned its bad reputation, and then demonstrates a respectable use: error cleanup during hardware initialisation, a pattern found in real embedded C programming and in the Linux kernel.

Like every part of this free C tutorial, the examples were compiled and run with GCC 13 so the output shown is real. If you want a free embedded C course that gives balanced advice instead of slogans, read on.

What You Will Learn

  • The language rules for labels and goto, with the real compiler error for each violation
  • Why a goto cannot leave its function
  • How to end a block with a label correctly
  • Why heavy goto use produces spaghetti code
  • The structured cleanup pattern for embedded initialisation code

Prerequisites

Complete the previous lecture on goto basics first. You should know what a label is and the difference between a forward and a backward jump. To reproduce the errors, compile the snippets with gcc -std=c11 -pedantic-errors.

Rule 1: A Label Lives Inside One Function

The scope of a label is the whole function that contains it. A goto in one function can never jump to a label in another. The compiler checks this and refuses to continue.

void first(void)
{
    goto fail;      /* label is in a different function */
}

void second(void)
{
fail:
    ;
}
error: label 'fail' used but not defined

If you need to leave a function early, use return. If you need a non-local jump across functions, the standard library provides setjmp and longjmp, but that is an advanced topic far beyond this chapter and rarely appropriate for beginners.

Rule 2: Each Label Name Appears Once Per Function

You may have many gotos pointing at one label, but you may not define the same label twice.

int main(void)
{
    int x = 0;
again:
    x++;
again:        /* second definition */
    x--;
    return x;
}
error: duplicate label 'again'

Labels have their own name space, so a label may share a name with a variable without clashing. Please do not take advantage of that; it only confuses readers.

Rule 3: A Label Must Be Followed by a Statement

In the C11 standard, a label is part of a statement. If a label sits at the very end of a block with nothing after it, the compiler complains. The fix is the null statement, a lone semicolon.

int main(void)
{
    goto end;
    printf("hi\n");
end:
}
error: label at end of compound statement
end:
    ;      /* null statement makes it legal */

For the same reason, in C11 a label cannot be followed directly by a declaration:

goto here;
here:
    int v = 5;      /* declaration, not a statement */
error: a label can only be part of a statement and a declaration is not a statement

Note: The newer C23 standard relaxes both restrictions, and recent compilers accept them in C23 mode. Writing a null statement after the label works in every version, so it is the portable habit.

Rule 4: Jumping Over an Initialisation Is Legal but Dangerous

C lets you jump forward past a declaration that has an initialiser. The variable exists after the label, but its initialiser never ran, so its value is indeterminate. Reading it is undefined behaviour. Compilers often warn with options such as -Wjump-misses-init, but you should avoid the situation entirely by declaring variables at the top of the function when you use goto.

Jumping into the scope of a variable-length array is not just dangerous but a constraint violation, and the compiler rejects it.

RuleWhat happens if broken
Label must be in the same functionCompile error: label used but not defined
Label name unique per functionCompile error: duplicate label
Label needs a following statement (C11)Compile error; add a null statement
Do not skip initialisersSilent bug: indeterminate value
Do not jump into a VLA scopeCompile error

Why Goto Has a Bad Reputation

In 1968 Edsger Dijkstra published a letter titled “Go To Statement Considered Harmful”, arguing that unrestricted jumps make it hard to reason about what a program has done at any given line. With structured statements you can read code top to bottom and know how you arrived. With free-form goto, any label may be reached from anywhere, so you must consider every jump source.

Structured flow vs tangled goto flow

Structured→init→loop→cleanup
Tangled→L1⇄L3⇄L2⇄L4
Reader→must trace every arrow to know the state

The result is called spaghetti code. It compiles and may even work, but it resists debugging, testing and modification. Tools such as static analysers and coding standards react accordingly: MISRA C:2012, widely used in automotive firmware, advises against goto and restricts it to forward jumps within the same or an enclosing block. Many teams simply forbid it.

The Respectable Use: Cleanup on Error

Real hardware initialisation has a nasty shape: enable the clock, open the UART, start the sensor, and if any step fails, undo only the steps that already succeeded. Doing that with nested ifs creates a staircase of indentation. A disciplined goto removes the staircase. The rule of the pattern is that all jumps go forward, to labels that undo resources in reverse order.

#include <stdio.h>

static int init_clock(void)  { printf("clock ready\n");   return 0; }
static int init_uart(void)   { printf("uart ready\n");    return 0; }
static int init_sensor(void) { printf("sensor FAILED\n"); return -1; }
static void deinit_uart(void)  { printf("uart released\n"); }
static void deinit_clock(void) { printf("clock released\n"); }

static int board_init(void)
{
    int err;

    err = init_clock();
    if (err)
        goto out;
    err = init_uart();
    if (err)
        goto undo_clock;
    err = init_sensor();
    if (err)
        goto undo_uart;
    return 0;

undo_uart:
    deinit_uart();
undo_clock:
    deinit_clock();
out:
    return err;
}

int main(void)
{
    int rc = board_init();
    printf("board_init returned %d\n", rc);
    return 0;
}
$ gcc -std=c11 -Wall cleanup.c -o cleanup
$ ./cleanup
clock ready
uart ready
sensor FAILED
uart released
clock released
board_init returned -1

Trace it. The sensor fails, so control jumps to undo_uart, which releases the UART and then falls through into undo_clock, releasing the clock, and finally reaches out to return the error code. If the UART had failed instead, only the clock would be released. The labels are ordered as a stack: later resources are undone first. This is the same convention used in many Linux kernel driver probe functions, and it is why experienced embedded engineers tolerate goto in this one role.

Cleanup chain: forward jumps only

init_clock→init_uart→init_sensor→return 0
sensor fails→undo_uart→undo_clock→out
uart fails→undo_clock→out
clock fails→out

Alternatives to Goto

  • Nested ifs: safe but the indentation grows with every resource.
  • Early returns with repeated cleanup: simple, but cleanup code is duplicated and easy to forget when you add a resource.
  • Flag variables: avoid jumps but add state that must be tested repeatedly.
  • Splitting into helper functions: often the cleanest answer; each function acquires and releases one resource.

Common Mistakes

  1. Jumping backward to build loops that a while would express better.
  2. Using vague labels like L1, L2, label.
  3. Reordering cleanup labels so a resource is released before the one that depends on it.
  4. Forgetting the null statement after a final label.
  5. Adding a new resource but forgetting to add its matching cleanup label.

Best Practices

  • If you use goto, jump forward only and only to labels near the end of the function.
  • Name labels after what they do: out, undo_uart, err_free.
  • Keep one return point at the bottom for the error path.
  • Follow your project’s coding standard. If the standard forbids goto, do not argue with the static analyser.
  • Declare variables at the top of the function so no jump can skip an initialiser.

Safety Considerations

In safety-critical products, the cost of a reasoning mistake is high, so reviewers prefer constructs they can verify mechanically. A cleanup chain that always jumps forward is easy to verify; a web of backward jumps is not. Resource leaks on rarely tested error paths are a real source of field failures in firmware, which is the argument for the cleanup pattern, but only when the labels and releases are kept in strict reverse order.

Summary and Key Takeaways

  • A label belongs to one function; goto cannot cross function boundaries.
  • Duplicate labels and labels without a following statement are compile errors in C11.
  • Jumping over an initialiser compiles but leaves the variable indeterminate.
  • Unrestricted goto produces spaghetti code and is discouraged by MISRA C and many teams.
  • The forward-only cleanup chain is the accepted exception in embedded C programming.

With the rules and the reasons clear, you are ready for the practical question the book poses next: how to leave several nested loops at once, which we tackle in the next lecture of this free C programming course.

Frequently Asked Questions

Can goto jump between functions in C?

No. A label is visible only inside its own function. A goto to a label elsewhere gives the error “label used but not defined”.

Why must a label be followed by a statement?

In C11 a label is defined as part of a statement. Use a null statement (a semicolon) when nothing else follows. C23 relaxes this.

Can two gotos use the same label?

Yes. Many gotos may target one label, but the label itself may be defined only once per function.

Why do people say goto is bad?

Unrestricted jumps make control flow hard to follow, which creates spaghetti code that is difficult to debug and maintain.

Is goto ever acceptable in embedded C programming?

Yes, for forward-only error cleanup in initialisation code, as in many Linux kernel drivers, as long as your coding standard permits it.

What does MISRA C say about goto?

MISRA C:2012 advises against it, and where it is used, jumps must go forward to a label in the same or an enclosing block.

Free C Tutorial for Embedded Engineers

Keep going through our free embedded C course. Next you will learn to exit nested loops cleanly.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →