'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
Example of register storage class is given below
- #include <stdio.h>
- int main( )
- { //Code block 1
- auto int a = 1;
- { //Code block 2
- auto int a = 2;
- { //Code Block 3
- auto int a = 3;
- printf ( "\n Value of 'a' in Code Block 3: %d", a);
- }
- printf ( "\n Value of 'a' in Code Block 2: %d", a);
- }
- printf ( "\n Value of 'a' in Code Block 1: %d", a);
- }
- Output:
- Value of 'a' in Code Block 3: 3
- Value of 'a' in Code Block 2: 2
- 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:
Post a Comment