Monday 31 October 2011

Variables and Data Storage

One of the C language’s strengths is its flexibility in defining data storage. There are two aspects that can be controlled in C: scope and lifetime. Scope refers to the places in the code from which the variable can be accessed. Lifetime refers to the points in time at which the variable can be accessed.

Three scopes are available to the programmer:

extern:


This is the default for variables declared outside any function. The scope of variables with extern scope is all the code in the entire program.


static:


The scope of a variable declared static outside any function is the rest of the code in that source file. The scope of a variable declared static inside a function is the rest of the local block.


auto:


This is the default for variables declared inside a function. The scope of an auto variable is the rest of the local block.


Three lifetimes are available to the programmer. They do not have predefined keywords for names as scopes do. The first is the lifetime of extern and static variables, whose lifetime is from before main() is called until the program exits. The second is the lifetime of function arguments and automatics, which is from the time the function is called until it returns. The third lifetime is that of dynamically allocated data. It starts when the program calls malloc() or calloc() to allocate space for the data and ends when the program calls free() or when it exits, whichever comes first.

No comments:

Post a Comment