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; 
}
2
  • 1
    Where is the recursion? Commented Dec 28, 2021 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? Commented Dec 28, 2021 at 20:24

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.