Categories
a. Storage Classes explanation

Register Storage Class in C

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 ClassDeclarationStorageDefault Initial ValueScopeLifetime
autoInside a function/blockMemoryUnpredictableWithin the function/blockWithin the function/block
registerInside a function/blockCPU RegistersGarbageWithin the function/blockWithin the function/block
externOutside all functionsMemoryZeroEntire the file and other files where the variable is declared as externprogram runtime
Static (local)Inside a function/blockMemoryZeroWithin the function/blockprogram runtime
Static (global)Outside all functionsMemoryZeroGlobalprogram runtime

Leave a Reply

Your email address will not be published. Required fields are marked *