I have a question regarding the answer in this question but I can not comment on it because I have less than 50 rep.
I was wondering in the answer foo()
is being called multiple times and the static variable is being assigned the same number of times. So why is it that the static variable is not reassigned to 10 each time?
You've got the shorter answer, but let me expand a bit on that.
Any object, has a storage duration. The storage duration determines the "lifetime" of the object (or variable).
Static storage is one of the storage durations, marked by keyword static
. Now, to elaborate on lifetime, let us check the relevant parts of the C11
standard, chapter §6.2.4.
From paragraph 2,
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address and retains its last-stored value throughout its lifetime. [....]
So, the last stored value is retained throughout the lifetime.
Now, for the objects with static storage duration, paragraph 3,
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.
Now, referring to your question, the statement you saw is the initialization and as per the rule specified, it happens only once (prior to program startup), so the initialization is not repeated over for multiple function calls. The variable retains the last-stored value.
Actually static
variables can get reassigned. But can't be redefined.
Once a static
variable defined it can't get redefined throughout the life time of program. But we can change the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With