http://en.cppreference.com/w/cpp/language/storage_duration
Static local variables
Static variables declared at block scope are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.
What is the meaning of 'static' in this quote? Is it:
static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends.
If so, then it doesn't explain what happens to int k;
in the main
or any other function in terms of initialization, because k
is not a static variable (it doesn't get allocated when the program begins and deallocated when the program ends - wait a second, you might say that the main
function starts running when the program begins and returns when the program ends, but that's not how it works I guess).
In the main function:
int k;
k++;
results in an error: uninitialized local variable 'k' used
.
So if k
above is not a static local variable, could you give an example of such variables?
And could anyone tell me why the following code compiles and runs without any issues, even though k
is not initialized?
Given a function with no body:
void foo(int* number) { }
And calling it like this in main
:
int k;
foo(&k);
k++;
It now compiles and runs with no problems, but the value of k
is -858993459. The compiler didn't like the fact I attempted to increment it without initiation, but passing it to foo
caused that the compiler forgot about it. Why?