Course contentsShow
← C
Lesson 147 of 1,2192. Variables and TypesFree lesson

Introduction to the `register` keyword

Introduction to the register keyword

What you'll learn: How to suggest to the compiler that a specific variable should be stored in the CPU’s fastest memory for maximum speed.

The Need for Speed

To understand the register keyword, imagine you are a chef in a kitchen. Most of your ingredients are kept in the pantry (RAM). Every time you need an onion, you have to walk across the room to get it, which takes time. However, you have a small cutting board right in front of you (the CPU registers). If you keep your knife and your most-used seasoning right there on the board, you can work much faster.

In C, a register variable is your attempt to keep a value "on the cutting board" instead of in the "pantry."

How it Works

When you declare a variable with the register keyword, you are giving the compiler a hint. You’re saying, "I am going to use this variable a lot, so please store it in the CPU's internal registers instead of the main RAM."

Registers are the fastest storage locations in your computer, but there are very few of them. Because space is so limited, the compiler might ignore your request if it runs out of room or thinks it has a better plan.

#include <stdio.h>

int main() {
    // We use 'register' for a counter because it is accessed 
    // thousands of times in a very short period.
    register int i;
    int sum = 0;

    for (i = 0; i < 10000; i++) {
        sum += i;
    }

    printf("The sum is: %d\n", sum);

    return 0;
}

The "No Address" Rule

Because a register variable might not live in the computer's RAM, it doesn't have a standard memory address. This leads to one very important rule in C: you cannot use the address-of operator (&) on a register variable.

If you try to find the "location" of a register variable, the compiler will throw an error. It’s like trying to find the street address of the knife in your hand—it’s not sitting in a bin with a label; it’s currently being used in flight!

Modern Reality

In the early days of C, programmers used register to manually optimize code. Today, modern compilers are incredibly smart and usually decide which variables to put in registers better than humans can. However, knowing the keyword is vital for understanding low-level hardware interaction and legacy codebases.

Key takeaway

The register keyword suggests the compiler store a variable in the CPU for speed, but it prevents you from taking the variable's memory address.