What are C Goto Statement Basics- Embedded C Training For Beginners

🚀 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 Statement Basics

Understand the goto statement in C: labels, forward jumps, backward jumps and the exact control flow, with embedded-style examples in this free C tutorial.

The goto statement in C is an unconditional jump: the program leaves the current line and continues at a named label somewhere else in the same function. It is the oldest control-flow tool in programming, older than structured loops, and it is both widely criticised and widely used in real embedded C programming. To judge it fairly you first need to understand precisely how it works, which is the goal of this lecture in our free C programming course.

This free C tutorial keeps the explanation practical. We build three small programs, look at the control flow as a diagram, and compare goto with the loops you already know. The next lecture covers the rules and the dangers; here we focus on the mechanism. If you are looking for a free embedded C course that explains why things behave the way they do, you are in the right place.

What You Will Learn

  • The syntax of the goto statement in C and what a label is
  • The difference between a forward goto and a backward goto
  • How goto can build a loop, and why a real loop is usually better
  • How to read goto-based flow using a control-flow diagram
  • How goto compares with if, loops and switch

Prerequisites

You need to know the if statement, relational operators and basic loops. Having read the previous lecture on the continue statement helps, because goto is the most powerful of the jump statements and builds on the same idea of moving control without finishing a block.

Goto Statement in C: Syntax

A goto has two parts that always appear together: the jump itself and the label it targets.

goto target_name;

    /* ... other statements ... */

target_name:
    statement;

The label is any valid C identifier followed by a colon. When the program executes goto target_name;, the very next statement to run is the one that follows the label. Labels are not variables and take no memory; they are just names for positions in the code that the compiler turns into addresses.

Anatomy of a goto jump

statement A→goto target;
↓ skippedstatement Bstatement C
target:→statement D→continues normally

Forward Goto and Backward Goto

Where the label sits relative to the goto decides the behaviour.

TypeLabel positionEffectTypical use
Forward gotoAfter the gotoStatements in between are skippedError exit, skipping a block
Backward gotoBefore the gotoStatements in between run againRetry, hand-made loop

Several different goto statements may point to the same label. What you cannot do is define the same label twice in one function; the next lecture shows the compiler error for that.

Example 1: Forward Goto in a Battery Check

This program classifies three battery readings. For each reading, a forward goto selects one of three labels, and a shared next label rejoins the flow.

#include <stdio.h>

int main(void)
{
    int levels[3] = {95, 55, 12};

    for (int i = 0; i < 3; i++) {
        int pct = levels[i];

        if (pct > 80)
            goto healthy;
        if (pct > 20)
            goto normal;
        printf("%d%% -> LOW, charge now\n", pct);
        goto next;
    healthy:
        printf("%d%% -> HEALTHY\n", pct);
        goto next;
    normal:
        printf("%d%% -> NORMAL\n", pct);
    next:
        ;
    }
    printf("Battery check complete\n");
    return 0;
}
$ gcc -std=c11 -Wall goto1.c -o goto1
$ ./goto1
95% -> HEALTHY
55% -> NORMAL
12% -> LOW, charge now
Battery check complete

Walk through the first reading, 95. The first if is true, so control jumps over everything to healthy:, prints, then jumps to next:. For 55, the first test fails, the second succeeds and control lands on normal:, which falls straight into next:. For 12, both tests fail and the LOW message prints before its own goto next. Notice the lonely semicolon after next:. A label must be followed by a statement, and an empty statement satisfies that rule.

An honest remark: an if-else ladder is clearer for this problem and you should normally write it that way. The example exists to show how the jumps move, not to recommend the style.

Example 2: Backward Goto as a Loop

Here a label sits above the goto, and the jump repeats a block, exactly as a loop would.

#include <stdio.h>

int main(void)
{
    int count = 5;

again:
    printf("T-minus %d\n", count);
    count--;
    if (count > 0)
        goto again;
    printf("Lift off\n");
    return 0;
}
T-minus 5
T-minus 4
T-minus 3
T-minus 2
T-minus 1
Lift off

The three ingredients of every loop are all present: an initialisation (count = 5), a body, and a condition that decides whether to repeat (count > 0). The equivalent while loop is shorter and states its intent in the header, which is why structured loops replaced this pattern.

Backward goto behaves like a loop

again:→print count→count–
↓count > 0 ?
yes→goto again (back up)
no→print Lift off

Example 3: Skipping Statements With a Forward Goto

#include <stdio.h>

int main(void)
{
    int mode = 1;

    printf("Step A\n");
    if (mode == 1)
        goto skip;
    printf("Step B (only when mode != 1)\n");
    printf("Step C (only when mode != 1)\n");
skip:
    printf("Step D\n");
    return 0;
}
Step A
Step D

Steps B and C are never executed because the jump lands past them. Change mode to 0, rebuild, and all four lines appear. This is the simplest possible picture of a forward goto, and it is worth running yourself to see the difference.

How the Compiler Sees Goto

On most processors a goto becomes a single unconditional branch instruction, such as b on ARM Cortex-M or jmp on x86. There is no hidden stack work and no run-time label table. That is why goto is cheap, and also why it is dangerous: nothing checks that the jump makes logical sense. The compiler only verifies that the label exists in the same function.

Structured statements are also compiled into jumps. A while loop is a label and a conditional branch; an if is a conditional branch over a block. In that sense goto is the raw material of every control statement. Structured statements simply hide the labels and guarantee a tidy shape.

Goto vs Other Control Statements

NeedBest toolWhy
Two-way decisionif / elseClear shape, no labels
Many-way choice on an integerswitchIntent is obvious
Repeat a blockfor / while / do-whileCondition and update are in one place
Skip one iterationcontinueStays inside the loop
Leave one loopbreakOnly the innermost loop
Leave several loops or clean up on errorgoto (carefully) or a function returnOnly structured option that jumps far

Real-World Uses of Goto

  • Centralised error handling: a driver initialisation function jumps to a cleanup block when any step fails. We build this in the next lecture.
  • Leaving nested loops: a single jump exits several loops at once; see the lecture after next.
  • State machines in generated code: code generators sometimes emit labels and jumps because they never need to be read by humans.
  • Retry logic: a short backward jump to re-attempt a bus transaction, though a loop is normally cleaner.

Common Mistakes

  1. Forgetting the colon after the label name, which makes the label a syntax error.
  2. Ending a block with a label and nothing after it. Add a null statement: label: ;
  3. Jumping backward without a condition that eventually fails, creating an infinite loop.
  4. Skipping a variable initialisation with a forward jump and then using the variable.
  5. Using goto when a simple if-else or loop would do.

Best Practices

  • Prefer structured statements first; reach for goto only when it is clearly simpler.
  • Jump forward, not backward. Forward jumps read like an early exit; backward jumps hide loops.
  • Use descriptive labels such as error_exit or done instead of L1.
  • Keep the label close to the goto so the reader never has to scroll.
  • Test every jump path, including the rarely used ones.

Summary and Key Takeaways

  • goto label; transfers control to the statement after label: in the same function.
  • A forward goto skips statements; a backward goto repeats them.
  • A label is an identifier followed by a colon, and must be followed by a statement.
  • Structured loops and if statements are almost always clearer.
  • The jump itself costs one branch instruction, but readability can cost a lot more.

You now understand the mechanism behind the goto statement in C. Next, in this free C programming course, we study the rules that limit goto, the reasons many coding standards discourage it, and the one pattern in embedded C programming where it genuinely helps.

Frequently Asked Questions

What does goto do in C?

It transfers control unconditionally to a labelled statement in the same function, skipping or repeating the code in between.

What is a label in C?

A label is an identifier followed by a colon that marks a position in a function so that a goto can jump to it.

What is the difference between forward and backward goto?

A forward goto jumps to a label further down and skips code. A backward goto jumps to a label above and causes code to run again.

Can goto replace a loop in C?

Technically yes, using a backward jump and a condition, but a for or while loop expresses the same idea more clearly and is the recommended choice.

Does goto make a program slower?

No. It compiles to one branch instruction. The real cost is code that is harder to read and maintain.

Is goto allowed in embedded C programming?

The language allows it, and some projects such as the Linux kernel use it for cleanup, but safety standards like MISRA C discourage it.

Continue Your Free Embedded C Course

Next up in this free C tutorial: the rules, pitfalls and the one embedded pattern where goto earns its place.

💬 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 →