Wednesday, December 23, 2009

Static Variable in C

STATIC VARIABLE in C:

Static Variable as Local Variable in a function:

Variables defined local to a function disappear at the end of the function scope. So when we call the function again, storage for variables is created and
values are reinitialized. So if we want the value to be extent throughout the life of a program, we can define the local variable as "static." Initialization is performed only at the first call and data is retained between func calls.

Had it been global variable, it would have been available outside the scope of the function, but static variable is not available outside the scope of a function (helpful in localizing errors - as it can't be changed outside the function scope).

Static Variable as Global Variable in a File:
The Scope of the variable is limited to the file only. It cannot be used outside the file. It also retains it's value throughout the life.
It works in a same way as namespace in C++, as the same variable with the same name can be used in another file and yet will be different from the static variable in the first file.

No comments:

Post a Comment