(C beginner alert)
Wikipedia define a static variable as, ".... a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program. "
Then it goes on to give an example in C:
#include <stdio.h>
void func() {
static int x = 0;
/* x is initialized only once across four calls of func() and
the variable will get incremented four
times after these calls. The final value of x will be 4. */
x++;
printf("%d\n", x); // outputs the value of x
}
int main() { //int argc, char *argv[] inside the main is optional in the particular program
func(); // prints 1
func(); // prints 2
func(); // prints 3
func(); // prints 4
return 0;
}
Here's my issue: variable x, when defined as static, doesn't hold its value for the entire run of the program. In fact, it does quite the opposite, namely, for any subsequent call of func(), it has the value it was assigned in the previous calling. It's only when I remove the static keyword that x retains its value of 0 no matter how many times func() is called.
So:
1) Is Wikipedia's explanation inaccurate/misleading, and if so, how would you better explain the nature of a static variable?
2) What is actually happening under the hood on the second and subsequent calls of func() such that the initialization of x to 0 is effectivey being ignored?
lifetime&extenthave to do effectively with describing how the variable remainsalivebeyond the normal scope of its logical block, not the value it holds or does not hold in memory.printfstatement ahead of the increment, the value of x would still increment. But the printf would record values starting from 0 rather than 1.