Static variable inside of a function in C -


void foo() {     static int x = 5;     x++;     printf("%d", x); }  int main() {     foo();     foo();     return 0; } 

what printed out? 6 6 or 6 7

and why?

there 2 issues here, lifetime , scope.

the scope of variable variable name can seen. here, x visible inside function foo().

the lifetime of variable period on exists. if x defined without keyword static, lifetime entry foo() return foo(); re-initialized 5 on every call.

the keyword static acts extend lifetime of variable lifetime of programme; e.g. initialization occurs once , once , variable retains value - whatever has come - on future calls foo().


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -