In typical implementations of C and C++ storage for local variables is allocated on the stack (see: Stack-based memory allocation) when the function is entered, and cleared from the stack when the function returns.
That you have seen a function use the same address for its variables on different calls is actually a coincedence. Try nesting your function calls within other calls and see what happens:
#include <stdio.h>
int funcTwo()
{
int nn = 5;
printf("funcTwo, &nn = %p\n", &nn);
}
int funcOne(int n)
{
int nn = n;
printf("funcOne, &nn = %p\n", &nn);
funcTwo();
}
int main(int argc, char **argv)
{
funcOne(5);
funcTwo();
return 0;
}
Sample output:
funcOne, &nn = 0x7fff96726b7c
funcTwo, &nn = 0x7fff96726b4c
funcTwo, &nn = 0x7fff96726b7c
Observe that &nn
is slightly different inside the two calls to funcTwo
. That's because one instance is called from inside funcOne
, which has its own local variable on the stack (as well as its parameter, return address and any additional space used to save processor register values for example). The additional stack usage pushes the address of variables in funcTwo
further up the stack (to a lower address, since the stack grows downwards on this architecture).