C Language | Structure Declarations | Register Variables - register

Ordinary variables are stored in main memory. A variable declared with register may be placed in a fast CPU register. The compiler decides whether to use a register in practice.

Storing Values in Registers

Some local variables are accessed frequently. For example, a loop that processes graphics may repeatedly use variables involved in pixel conversion. It is reasonable to store frequently accessed values in faster memory.

C lets you declare such a variable as a register variable. Registers are fast storage locations inside the CPU.

Ordinary variables are stored in main memory. Registers can be faster because the CPU does not need to transfer values from main memory before processing them.

register Specifier

register type variableName ...

Register count and size depend on the physical computer. A compiler may ignore a register declaration and handle the variable normally if storing it in a register is not appropriate.

Because register variables are not necessarily stored in main memory, you cannot request their addresses.

Code 1

#include <stdio.h>

int main() {
 register int i;
 register int k;

 i = 5;
  k = i * 3;

  printf("i = %d, k = %d\n" , i, k);
 return 0;
}

This code declares i and k as register variables. Whether they are actually stored in registers depends on the compiler.

Modern compilers optimize code effectively, so developers rarely need to use the register specifier today.