1. local variable
change lifetime, keep scope
move the var stored in stack to static/global area , so during compile it will have a memory address, and memory address keeps live until program ends. But scope keep the same, eg. inside counter() , it always work only inside counter() .
void counter ( ) { int normal_var = 0 ; // Created and destroyed on EVERY call static int static_var = 0 ; // Created ONCE, stays in memory forever
normal_var ++ ; static_var ++ ;
std :: cout << "Normal: " << normal_var << " | Static: " << static_var << "\n" ; }
int main ( ) { counter ( ) ; // Normal: 1 | Static: 1 counter ( ) ; // Normal: 1 | Static: 2 counter ( ) ; // Normal: 1 | Static: 3 return 0 ; }
Enter fullscreen mode
Exit fullscreen mode
we can share the local var by its static address, which means return the address (pointer or reference), but this is bad practice( Broken Encapsulation and thread safety ).…