You can use the register storage class when you want to store local variables within functions or blocks in CPU registers instead of RAM to have quick access to these variables. For example, “counters” are a good candidate to be stored in the register.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular block. The only difference is that the variables declared using register storage class are stored inside CPU registers instead of a memory. Register has faster access than that of the main memory.
The variables declared using register storage class has no default value. These variables are often declared at the beginning of a program.
#include <stdio.h> /* function declaration */ main() { {register int weight; int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a memory location when dealing with CPU register*/} }
OUTPUT:
error: address of register variable 'weight' requested
The next table summarizes the principal features of each storage class which are commonly used in C programming
Storage Class | Declaration | Storage | Default Initial Value | Scope | Lifetime |
auto | Inside a function/block | Memory | Unpredictable | Within the function/block | Within the function/block |
register | Inside a function/block | CPU Registers | Garbage | Within the function/block | Within the function/block |
extern | Outside all functions | Memory | Zero | Entire the file and other files where the variable is declared as extern | program runtime |
Static (local) | Inside a function/block | Memory | Zero | Within the function/block | program runtime |
Static (global) | Outside all functions | Memory | Zero | Global | program runtime |