Thursday, 16 January 2014

What is scope & storage allocation of register, static and local variables in c

What is scope & storage allocation of register, static and local variables

Register variables: belong to the register storage class and are stored in the CPU registers. The scope of the
register variables is local to the block in which the variables are defined. The variables which are used for more number of times in a program are declared as register variables for faster access.
Example: loop counter variables.register int y=6;
Static variables: Memory is allocated at the beginning of the program execution and it is reallocated only after
the program terminates. The scope of the static variables is local to the block in which the variables are defined.
Example:
#include <stdio.h>
void decrement(){
static int a=5;
a--;
printf("Value of a:%d\n", a);
} int main(){
decrement();
return 0;
}
Here 'a' is initialized only once. Every time this function is called, 'a' does not get initialized. so output would be 4
3 2 etc.,
Local variables: are variables which are declared within any function or a block. They can be accessed only by function or block in which they are declared. Their default value is a garbage value.

No comments:

Post a Comment