Possible Duplicate:
What does “static” mean in a C program?
What does the static
keyword mean in C ?
I'm using ANSI-C. I've seen in several code examples, they use the static
keyword in front of variables and in front of functions. What is the purpose in case of using with a variable? And what is the purpose in case of using with a function?
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
"In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.
In C, inside a function, we use the static modifier to declare variables with static storage duration. Such variables retain their value throughout multiple calls of the function. These variables are initialized only once at compile time. Their life time matches the life time of our program.
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.
Just as a brief answer, there are two usages for the static
keyword when defining variables:
1- Variables defined in the file scope with static
keyword, i.e. defined outside functions will be visible only within that file. Any attempt to access them from other files will result in unresolved symbol at link time.
2- Variables defined as static
inside a block within a function will persist or "survive" across different invocations of the same code block. If they are defined initialized, then they are initialized only once. static
variables are usually guaranteed to be initialized to 0
by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With