Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does a static variable not get reassigned when inside the function

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?

like image 343
J.Doe Avatar asked Mar 30 '17 05:03

J.Doe


2 Answers

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 specifier static, 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.

like image 182
Sourav Ghosh Avatar answered Oct 18 '22 23:10

Sourav Ghosh


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.

like image 35
Jayesh Avatar answered Oct 19 '22 00:10

Jayesh