Course contentsShow
← C
Lesson 306 of 1,2194. Control FlowFree lesson

Defining labels in C code

Defining labels in C code

What you'll learn: How to create named markers in your source code that serve as destinations for the goto statement.

The Bookmark in Your Code

In programming, we usually think of code as a straight waterfall, flowing from the top line to the bottom. However, sometimes you need to tell the computer to "jump" to a specific spot elsewhere in the function. To do this, you need a label.

Think of a label as a sticky note or a bookmark you place on a page. The bookmark itself doesn't "do" anything—it doesn't add numbers or print text—it simply names a location so you can find it instantly later.

How to Syntax

In C, a label is created by writing a name followed by a colon (:). You can place a label on its own line or directly before a statement.

#include <stdio.h>

int main() {
    int count = 0;

    // This is a label named 'start'
    start: 
    
    count++;
    printf("Count is: %d\n", count);

    if (count < 3) {
        goto start; // Tells the program to jump back to the 'start' label
    }

    // This is a label named 'end'
    end:
    printf("Program finished.\n");

    return 0;
}

Rules for Naming Labels

Labels follow the same naming rules as variables:

  1. They must start with a letter or an underscore.
  2. They can contain letters, numbers, and underscores.
  3. They are case-sensitive (MyLabel is different from mylabel).

The most important rule, however, is scope. A label only exists within the function where it is defined. You cannot create a label in main() and try to jump to it from a different function.

Why use them?

While modern C programming discourages heavy use of labels because they can make code messy (often called "spaghetti code"), they remain a valid part of the language. They are most commonly seen in low-level systems programming for centralized error handling, where multiple points in a function might need to jump to a single "cleanup" label at the bottom.

Key takeaway

A label is a named identifier followed by a colon that marks a specific location in your code for the goto statement to target.