I am reading the concept of language ch 5 and find that
static's disadvantage : subprograms cannot share same storage.
stack-dynamic's advantage : without recursion, it is not without merit subprograms can share the same memory space for theirs locals.
and I think that due to static bound from begin to terminal, all subprogram should can see it and use
it
like the code I test
#include<iostream>
static int test = 0;
void func1(){ cout << test++ << endl;}
void func2(){ cout << test++ << endl;}
int main(){
func1();
func2();
}
and stack-dynamic allocation each time execute the function, like being push to stack(LIFO), so they
are in different momory space.
I don't know where is the error in my thought?
Thx in advance.
You program runs in a dedicated memory space. Static variables have global scope. Given that, I suppose "Subprograms cannot share same storage" means that static variable is instantiated only once and it's the same object during the entire lifetime of the program. This has several consequences:
Dynamically allocated/stack variables use the same memory space in which the program runs, but they can be instantiated many times, and the instances are independent of each other. E.g., if stack variable is defined inside a function, it's allocated upon function entry and released upon function exit. If the function is entered again, new variable will be created. It's same memory space, but different stack frame in this space.