Tuesday, April 17, 2012

Register storage class in C!!

Register storage class is used to store the local variable in the CPU memory. This is similar to auto variable except storing the data in CPU memory instead of main memory. So there wont be any address for the register variables, because it stores in CPU memory called registers.  As there are only limited registers in the CPU, There is no guarantee that all register variables are stores in CPU memory. If CPU memory is full (no register variables available), it stores in main memory. We are only intimating to the compiler as a register variable. It completely depends on the compiler whether to store in CPU memory or main memory. So its better to declare register variables only if needed. Accessing register variable is very quick and efficient.
  • Keyword : register
  • Default value : Garbage value
  • Memory Location : CPU memory (Registers)
  • Scope : Local to the block or function
  • Lifetime : till CPU memory resets or end of the application/program 

 Sample Code for Register storage Class:
main()
{
    register r = 20;
    printf("r value is %d\n",r);
    //printf("r address is %d\n",&r); // can't access address of the register variable
}

Output:
r value is 20

Output : When try to access the address of the register variable, got the following error
reg.c: In function 'main':
reg.c:6: error: address of register variable 'r' requested

 Accessing the address of the register variable is illegal as it doesn't have any address. So '&' unary operation fails on register storage class. Register can be used for the variables which can be used frequently like counters  and need quick access.

No comments:

Popular Posts