0

I have this C function with a static variable:

void plus_five() {
    static int i = 10;
    i += 10;
    printf("%d", i);
}

int main() {
    for(int i = 0;i < 10;i++) {
        plus_five();
    }
    return 0;
}

I get this output: 10 20 30 40 50 60 70 80 90 100

Why does the variable get incremented even when it is set to 10 every time the function is executed?

adsf
  • 59
  • 5
  • Because that's exactly what a static variable does. It's not a local variable (where a fresh copy is made for every call to the function). It's just one single memory location, that's reused every time. – Alexander Jan 24 '23 at 20:10
  • https://stackoverflow.com/questions/572547/what-does-static-mean-in-c?rq=1 – yad0 Jan 24 '23 at 20:11
  • @Alexander: The identifier for an object declared with `static` inside a function is local; its scope is limited to the smallest enclosing block. The lifetime of the object is static, as contrasted with the default automatic lifetime for objects defined inside functions. – Eric Postpischil Jan 24 '23 at 20:23

3 Answers3

0

Variables declared inside of a function as static are initialized once at program startup and retain their value through successive function calls.

This means the first time plus_five is called i will have the value 10, and the function will increase the value to 20. On the next call, i has retained its value of 20 and is increased to 30, and so forth.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

Why does the variable get incremented even when it is set to 10 every time the function is executed?

Because you marked it static, which means (in this context) that you want the variable to persist for the entire life of the program. The variable only gets initialized once, and from then on it keeps whatever value you give it.

Think of a static variable as a global variable that's only visible from inside the function where it's declared.

Caleb
  • 124,013
  • 19
  • 183
  • 272
0

'Why does the variable get incremented even when it is set to 10 every time the function is executed?' is a wrong question.

The variable actually is incremented. It is incremented due to the i += 10 expression, and it doesn't depend on being (or not being) 'set to 10 every time the function is executed'.

Now the actual question is not 'whether/why the variable is/is not incremented' but rather 'why the variable is not re-initialized to 10 on every execution of the function?'

And the answer is: because that's what the keyword static means: the variable is initialized only once and preserves its value between calls to the function.

CiaPan
  • 9,381
  • 2
  • 21
  • 35