Difference between Static variables and Register variables in C
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
static data_type var_name = var_value;
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in the register.
register data_type var_name = var_value;
Differences between static variables and register variables in C.
Static Variables Register Variables Keyword used is – “static”. Keyword used is – “register”. Static variable may be internal or external depending on the place of declaration. Register variables are declared inside a function. Internal static variables are similar to auto variables or local variables. Whereas, external static variables are similar to global variables. Register variables are similar to auto or local or internal variables. The execution speed is slower than register variables. The register variables leads to faster execution of programs. Internal static variables are active(visibility) in the particular function and External static variables are active in the entire program. Register variables are active only within the function. Internal static variables are alive(lifetime) in until the end of the function and External static variables are alive in the entire program. Register variables are alive until the end of a function. Static variables stored in initialized data segments. Register variables are stored in registers. Static variable is stored in the memory of the data segment. In register variables, CPU itself stores the data and access quickly.