C register storage class



We know the basic concept of storage class in c programming. In this tutorial we will be learning the register storage class.

Register Storage Class :

  1. register keyword is used to define local variable.
  2. Local variable are stored in register instead of RAM.
  3. As variable is stored in register, the Maximum size of variable = Maximum Size of Register
  4. unary operator [&] is not associated with it because Value is not stored in RAM instead it is stored in Register.
  5. This is generally used for faster access.
  6. Common use is “Counter

Syntax

{
register int count;
}

Register storage classes example

#include<stdio.h>

int main()
{
int num1,num2;
register int sum;

printf("\nEnter the Number 1 : ");
scanf("%d",&num1);

printf("\nEnter the Number 2 : ");
scanf("%d",&num2);

sum = num1 + num2;

printf("\nSum of Numbers : %d",sum);

return(0);
}

Explanation of program

Refer below animation which depicts the register storage classes –

register storage class
Reference : [cprogrammingexpert]

  1. In the above program we have declared two variables num1,num2. These two variables are stored in RAM.
  2. Another variable is declared which is stored in register variable.Register variables are stored in the register of the microprocessor.Thus memory access will be faster than other variables.
  3. If we try to declare more register variables then it can treat variables as Auto storage variables as memory of microprocessor is fixed and limited.

Why we need Register Variable ?

  1. Whenever we declare any variable inside C Program then memory will be randomly allocated at particular memory location.
  2. We have to keep track of that memory location. We need to access value at that memory location using ampersand operator/Address Operator i.e (&).
  3. If we store same variable in the register memory then we can access that memory location directly without using the Address operator.
  4. Register variable will be accessed faster than the normal variable thus increasing the operation and program execution. Generally we use register variable as Counter.

Note : It is not applicable for arrays, structures or pointers.

Summary of register Storage class

Keyword register
Storage Location CPU Register
Initial Value Garbage
Life Local to the block in which variable is declared.
Scope Local to the block.