Hello World !!
Today I was reading a topic on 'Local Variables' from 'Thinking in C++ by Bruce Eckel', there Bruce has mentioned that "variables defined local to a function disappear at the end of the function scope. When you call a function again, storage for the variables is created anew and the values are reinitialized."
Now from this I inferred:
Inference 1. variables local to a scope get destroyed as soon as their scope ends.
Say, when we call a function again and again, all its variables are allocated new memory locations and as soon as the function execution gets over all the memory locations are set free.
And I wrote the following code to seal my inference
Code:
#include<iostream>using namespace std;
void func()
{
int i;
cout<<"Address of i in func(): "<<(long)&i<<endl;
}
int main()
{
int i;
cout<<"The Address of i in main(): "<<(long)&i<<endl;
for(int i=0;i<3;i++)
{
func();
}
cout<<"The Address of i in main() again: "<<(long)&i<<endl;
func();
return 0;
}
The results were as follows:
Code:
The Address of i in main(): 2293512
Address of i in func(): 2293468
Address of i in func(): 2293468
Address of i in func(): 2293468
The Address of i in main() again: 2293512
Address of i in func(): 2293468
According to Inference 1, on every func() call, 'int i' inside it should have been allocated different memory location, whereas here I see that on every func() call the memory location allocated to 'int i' is same
from the results of the above code I am forced to infer this:
Inference 2: for every func() call, the variables disappear at the end of the func() execution and the memory is set free but this freed memory still resides in the big memory chunk allocated to the program at the beginning of its execution, so at the beginning of every func() call the compiler does allocate anew memory location to 'int i' but every time it allocates the memory it lays its hands on the readily available memory locations which turn out to be the same in all the func() calls.
this may explain the same memory address for 'int i' on every call
so my question is: which of the two inferences is true or are they both a big fat fallacy ?
friends, please help me out, I am just a humble beginner of C++