C: How does C "ignore" subsequent initializations of local function variables when static? -


(c beginner alert)

wikipedia define static variable as, ".... variable has been allocated statically—whose lifetime or "extent" extends across entire run of program. "

then goes on give example in c:

#include <stdio.h>  void func() {     static int x = 0;      /* x initialized once across 4 calls of func() ,       variable incremented 4        times after these calls. final value of x 4. */     x++;     printf("%d\n", x); // outputs value of x }  int main() { //int argc, char *argv[] inside main optional in particular program     func(); // prints 1     func(); // prints 2     func(); // prints 3     func(); // prints 4     return 0; } 

here's issue: variable x, when defined static, doesn't hold value entire run of program. in fact, quite opposite, namely, subsequent call of func(), has value assigned in previous calling. it's when remove static keyword x retains value of 0 no matter how many times func() called.

so:

1) wikipedia's explanation inaccurate/misleading, , if so, how better explain nature of static variable?

2) happening under hood on second , subsequent calls of func() such initialization of x 0 effectivey being ignored?

you misunderstand quoted explanation. means variable's "lifetime" extends whole program is allocated in memory once, initialized once, , changes made reflected @ same memory location--that memory allocated life of program. subsequent calls function find contents of memory (the value of x) left it. still allowed change value, same piece of memory.

when remove "static", you're telling compiler allocate new variable "x" each time function called, assign 0, , discard when function returns. on next call, entirely different variable x created, assigned 0 again, , discarded again. variable's "lifetime" inside function.

this entirely separate concept variable's "scope", can see , change variable: it's scope still inside function, when static.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -