+ 2
What is the use n application of Static variables in C?
2 ответов
+ 4
When you want a variable that is only initialized once for a function that is called multiple times.
+ 2
Lets say that you have a function that gets executed every time an even triggers.. (ej. a 1s timer callback)
If you want to increment a minute counter, you have to count how many times the function gets executed...
This may be implemented with a global variable:
int seconds = 0; // global for counting seconds
int minutes = 0;
void timer_callback(){
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
}
int main(){
<some code>
}
If you want to make "seconds" local (because globals are evil :P ), but you need seconds to keep it's value -like a global do- you can declare as static (inside the function):
int minutes = 0;
void timer_callback(){
static int seconds = 0; // seconds is static
seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
}
int main(){
<some code>
}
As "seconds" is static, is local to timer_callback() -so it's "invisible" to the rest of the program- but don't lose it's value when function ends...
Note: It gets initialized (in this example to 0) ONLY the first time the function is called...
Hope that this example helps you... :)