0

Does static variable initialize only one time? does it ignore its initialize statement static int i=1, so it won't set it to 1 again so does it read it only first time then it ignores? how does it this work. if function called again and again, can anyone explain this? Output: 123

#include<stdio.h>

void  increment();  
int main() 
{ 
    increment(); 
    increment(); 
    increment(); 
} 

void  increment() 
{ 
    static int i = 1 ; 
    printf("%d",i); 
    i=i+1; 
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
MaxX
  • 33
  • 6
  • 1
    Where is the recursion? – Cid Dec 28 '21 at 17:47
  • I find it interesting that you have a minimal example that shows that this is exactly how it works. And still you ask the question, like you don't believe it. What else did you expect? – Cheatah Dec 28 '21 at 20:24

3 Answers3

1

According to the C Standard *5.1.2 Execution environments)

  1. ... All objects with static storage duration shall be initialized (set to their initial values) before program startup.

A function local static variable keeps its values between function calls.

So the program will output

123
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

As a mental model of what is happening, your increment function works as if it was rewritten as:

static int foo_i = 1;
void  increment() 
{ 
    printf("%d",foo_i); 
    foo_i=foo_i+1; 
}

Naturally there won't exist a variable named foo_i, and if the compiler does that kind of rewriting it will use a unique name for foo_i that doesn't pollute the namespace of valid c-identifiers.

HAL9000
  • 2,138
  • 1
  • 9
  • 20
0

Variables declared as static are initialized once at program startup. When a function with a static variable is called a subsequent time, the value is retained from the prior call.

In this particular case, the first call to increment prints "1", then "2" for the second call, then "3" for the third call.

dbush
  • 205,898
  • 23
  • 218
  • 273