Reputation: 69
I'm trying to learn how static variable work in c for when they are defined in a given function. For example, when I write the following:
#include <stdio.h>
void inc() {
static int c = 0;
c++;
printf("%d\n", c);
}
int main(void) {
inc();
inc();
inc();
return 0;
}
The expected output is obviously:
1
2
3
On the first call of the function, the static variable c is defined and given the value of 0, which makes perfect sense. It is the incremented and printed. However, on the second call to inc()
why is it that the integer c is maintained and not set to zero, even though the code literally says static int c = 0;
. What mechanism in the compiler stops c from having it's value set to zero like during the first call?
Upvotes: 1
Views: 491
Reputation: 134286
Quoting C11
, chapter §6.2.4, Storage durations of objects (emphasis mine)
An object whose identifier is declared without the storage-class specifier
_Thread_local
, and either with external or internal linkage or with the storage-class specifierstatic
, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
So, the initialization inside the function call does not take place on every call to the function. It only happens once, before the execution of main()
starts. The variable retains the last stored value through the program execution, i.e, the value is retained between the repeated calls to the function.
Upvotes: 7
Reputation: 1
Its lifetime is the entire execution of the program and its valie is intialized before program starts and only once.
Upvotes: -1