The register storage class is used to suggest that a variable should be stored in a CPU register instead of main memory for faster access. Since registers are faster than memory, register variables are generally used for frequently accessed data.
- The register keyword provides a hint to the compiler for optimization.
- Modern compilers often perform register allocation automatically.
Address of a Register Variable Cannot Be Accessed
A register variable may be stored in a CPU register instead of memory. Therefore, using the address-of (&) operator with a register variable is not allowed.
#include <stdio.h>
int main(){
register int i = 10;
int *ptr = &i;
return 0;
}
Output
./Solution.c: In function 'main':
./Solution.c:7:5: error: address of register variable 'i' requested
7 | int *ptr = &i;
| ^~~
Register Can Be Used with Pointer Variables
A pointer variable itself can be declared as a register variable because the memory address stored by the pointer can reside in a CPU register.
#include <stdio.h>
int main(){
int x = 10;
register int *ptr = &x;
printf("%d", *ptr);
return 0;
}
Output
10
Register Cannot Be Used with Static
The register and static keywords are both storage class specifiers. Since a variable can have only one storage class, they cannot be used together.
#include <stdio.h>
int main(){
register static int x = 10;
return 0;
}
Output
./Solution.c: In function 'main':
./Solution.c:5:5: error: multiple storage classes in declaration specifiers
5 | register static int x = 10;
| ^~~~~~~~
Register Variables Cannot Be Declared Globally
The register storage class can only be applied to local variables declared inside a function or block. It cannot be used for global variables.
#include <stdio.h>
// error (global scope)
register int x = 10;
int main()
{
// works (inside a block)
register int i = 10;
printf("%d\n", i);
printf("%d", x);
return 0;
}
Output
error: register name not specified for 'x'
There Is No Fixed Limit on Register Variables
C does not impose a limit on the number of register variables that can be declared in a program. However, the compiler decides which variables are actually stored in CPU registers based on the available registers and optimization settings.
- Register variables provide faster access than ordinary local variables.
- The compiler may ignore the register keyword if sufficient registers are not available.
- The address of a register variable cannot be obtained using the & operator.
- Register variables are local to a function or block.
- Modern compilers usually handle register allocation automatically, making explicit use of register less common today.