Monday, April 4, 2016

'Register' Storage Class Specifier

'register' storage class is same as 'auto' except that 'register' variables are stored in CPU registers compared to 'auto' where 'auto' variables are stored in RAM. The scope of 'register' class variable is same as 'auto' class variable, i.e. they can't be accessed outside the code block they are declared. 'register' variables will also be initialized with garbage value.

Example of register storage class is given below
  1. #include <stdio.h>
  2. int main( )
  3. { //Code block 1
  4.  
  5. auto int a = 1;
  6. { //Code block 2
  7.  
  8. auto int a = 2;
  9. { //Code Block 3
  10.  
  11. auto int a = 3;
  12. printf ( "\n Value of 'a' in Code Block 3: %d", a);
  13. }
  14. printf ( "\n Value of 'a' in Code Block 2: %d", a);
  15. }
  16. printf ( "\n Value of 'a' in Code Block 1: %d", a);
  17. }
  18.  
  19. Output:
  20. Value of 'a' in Code Block 3: 3
  21. Value of 'a' in Code Block 2: 2
  22. Value of 'a' in Code Block 1: 1
Since CPU register access is faster than memory access, declaring frequently accessed variables as 'register' will improve the performance of program. But one important thing to note about 'register' variable is, it's not guaranteed that those variables will be stored in CPU registers because number of registers is very limited for a CPU. So, if all the registers are allocated for other variables or purposes, then a variable will get stored in RAM even if it's declared as 'register' type.


Also, you cannot request address of a register variable using address operator (&). This will result in compilation error because 'register' variables might not be stored on RAM.

No comments: