The register keyword and its modern relevance
What you'll learn: How to use the register keyword to suggest high-speed storage for variables and why modern compilers usually ignore this hint.
The Need for Speed
In the early days of C, programmers had to help the computer manage its memory manually. The CPU has a very small number of "registers"—tiny slots of memory sitting directly inside the processor. Accessing data in a register is instantaneous, whereas accessing data in the system RAM (Random Access Memory) is like driving across town to a warehouse.
The register keyword was created as a hint to the compiler: "This variable is going to be used constantly (like a loop counter), so please keep it in a CPU register instead of RAM to make the program faster."
How to Use It
You use register just like static or auto, placing it before the data type.
#include <stdio.h>
int main() {
// Hinting that 'i' should be kept in a CPU register
register int i;
int sum = 0;
for (i = 0; i < 1000; i++) {
sum += i;
}
printf("Sum: %d\n", sum);
return 0;
}
The Golden Rule: No Addresses
There is one strict rule when using register: you cannot use the address-of operator (&) on a register variable.
Think of it this way: The & operator asks for a memory address in the RAM "warehouse." If a variable is living inside the CPU's internal "pocket," it doesn't have a RAM address. If you try to do &i on a register variable, the compiler will throw an error, even if it didn't actually put the variable in a register.
Modern Relevance: The Smart Compiler
Today, the register keyword is mostly a relic of the past. Modern compilers (like GCC or Clang) are incredibly smart at "Optimization." They analyze your code and decide which variables deserve a register far better than a human can.
In fact, most modern compilers simply ignore the register keyword entirely. They will put a variable in a register if it makes sense, whether you asked them to or not. The only lasting effect of the keyword today is that it prevents you from taking the variable's address, which can occasionally help the compiler optimize a tiny bit more because it knows the variable won't be modified indirectly via a pointer.
Key takeaway
The register keyword is a legacy hint to store variables in the CPU for speed, but modern compilers handle this automatically and usually ignore the request.