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?
Your last question suggests you’re asking about the case where
staticis used in a local variable declaration.That’s implementation-specific.
Yes, locals declared with
staticreside in static storage.It’s the runtime that executes the initialization only once.
staticlocals are value-initialized, unless otherwise noted.