Menu

C++ Notes: static
📰

C++ Notes: static

DEV Community: cpp·Cheedge Lee·9 days ago
#RVDIf3pB
#devtocpp#devto#dev#include#static
Long article (888 words) — no AI summary yet.
Reading 0:00
15s threshold

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 ).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.