ProAnswers.org

Describe about storage allocation and scope of global, extern, static, local and register variables?

Globals have application-scope. They’re available in any compilation unit that includes an

appropriate declaration (usually brought from a header file). They’re stored wherever the linker puts them, usually a place called the “BSS segment.”

Extern? This is essentially “global.”

Static: Stored the same place as globals, typically, but only available to the compilation unit that contains them. If they are block-scope global, only available within that block and its subblocks.

Local: Stored on the stack, typically. Only available in that block and its subblocks.

(Although pointers to locals can be passed to functions invoked from within a scope where that local is valid.)

Register: See tirade above on “local” vs. “register.” The only difference is that

the C compiler will not let you take the address of something you’ve declared as “register.”

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

void decrement(){

static int a=5;

a–;

printf("Value of a:%d
", 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.