Reputation: 2223
How does the static
keyword works internally? Considering the base definition static variable is initialized only once
, how does the run-time
or compile
time interprets it in terms of execution flow? Consider code snippet:
void function()
{
static int count=0;
count++;
}
main()
{
for(int i=0;i<=10;i++)
function();
}
The line static int count=0;
is executed only once and that to in iteration i=0
is the best explanation I can come up with. Is it correct or does it work some other way?
And where in memory is a static variable stored stack
or heap
?
Also is there something called static object
in Objective-C
? If there is how is it different from normal object?
Upvotes: 0
Views: 540
Reputation: 85
It means something to the compiler and to the way memory is allocated depending on where it is. Inside a function variables are allocated on the stack and persist for the life of the function and the value is not retained between calls. With a static
declaration the variable is allocated where globals are allocated (usually .bss) and the value persists between function calls but the scope of the variable is only to that function.
When static
is used for global declarations outside of a function then the variable only has scope in that module. That is if you declare a static variable in module1.cpp then module2.cpp cannot access it with extern.
Upvotes: 2
Reputation: 258618
Your last question suggests you're asking about the case where static
is used in a local variable declaration.
How does the static keyword work internally?
That's implementation-specific.
Does this have anything to do with the memory being allocated?
Yes, locals declared with static
reside in static storage.
does the compiler/runtime just skip it after the first encounter?
It's the runtime that executes the initialization only once. static
locals are value-initialized, unless otherwise noted.
Upvotes: 5