Skip to content

About static local in scopes especially in funtions and how to use them#22

Open
Butcher3Years wants to merge 1 commit intoOptimising-usage----(std-vector)from
Local-static
Open

About static local in scopes especially in funtions and how to use them#22
Butcher3Years wants to merge 1 commit intoOptimising-usage----(std-vector)from
Local-static

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

Local Static Variables – The "Once Per Function" Magic 🪓

Branch: local-static
From The Cherno's C++ series — the part where he explains why static inside a function is weirdly powerful and surprisingly useful.

What is a Local Static Variable?

A variable declared inside a function with the static keyword.

void func() {
    static int counter = 0;   // ← local static
    counter++;
    std::cout << "Called " << counter << " times\n";
}



Lifetime = entire program (like global statics)
Scope = only inside the function (can't access outside)
Initialization = happens only once (first time function is called)
Stored in static storage (not stack) — survives function exits



class Singleton {
public:
    static Singleton& Get() {
        static Singleton instance;   // ← local static = thread-safe singleton
        return instance;
    }
private:
    Singleton() {}                   // private ctor
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant