Course contentsShow
← C
Lesson 961 of 1,21913. Advanced CFree lesson

Direct register access

Direct register access

What you'll learn: How to use the register keyword and inline assembly to interact directly with the CPU's high-speed storage.

The CPU’s Private Desk

Imagine your computer’s RAM is a massive warehouse. Even though it's fast, the CPU still has to "walk" down the aisles to grab data, which takes time. To speed things up, the CPU has a few private drawers right on its desk called registers. These are the fastest storage locations in your computer.

Usually, the C compiler decides which variables deserve a spot in these precious drawers. However, when you are writing low-level code—like a device driver or a high-performance math library—you might want to suggest or force the CPU to keep a specific value within arm's reach.

Hinting with the register Keyword

In standard C, you can use the register keyword. This acts as a hint to the compiler, saying: "I’m going to use this variable constantly; please keep it in a CPU register if you can."

#include <stdio.h>

int main() {
    // Suggesting to the compiler to store 'counter' in a register
    register int counter = 0;

    for (counter = 0; counter < 1000; counter++) {
        // High-speed operations happen here
    }

    printf("Counter reached: %d\n", counter);
    return 0;
}

Note: Because a register lives on the CPU and not in RAM, you cannot use the address-of operator (&) on a register variable.

Taking Control with Inline Assembly

Sometimes a hint isn't enough. If you need to move data into a specific register (like the eax register on x86 processors) to talk to hardware, you use Inline Assembly. This allows you to write "raw" machine instructions directly inside your C code using the asm keyword.

int result;
int input = 42;

// Moving a value into a register using GCC-style inline assembly
asm ("movl %1, %%eax;"  // Move 'input' into the EAX register
     "movl %%eax, %0;"  // Move EAX into 'result'
     : "=r" (result)    // Output
     : "r" (input)      // Input
     : "%eax"           // Clobbered register
    );

By bypassing the "warehouse" of RAM and working directly in the "desk drawers" of the CPU, your code can achieve the absolute maximum speed possible, interacting with the hardware at its most fundamental level.

Key takeaway

Direct register access bypasses system memory to store data directly on the CPU for maximum performance and hardware control.