The static keyword and its various uses in C++

The keyword static is one which has several meanings in C++ that I find very confusing and I can never bend my mind around how its actually supposed to work.

From what I understand there is static storage duration, which means that it lasts for the lifetime of the program in the case of a global, but when you’re talking about a local, it means that it’s zero initialized by default.

The C++ Standard says this for class data members with the keyword static:

3.7.1 Static storage duration [basic.stc.static]

3 The keyword static can be used to declare a local variable with static storage duration.

4 The keyword static applied to a class data member in a class definition gives the data member static storage duration.

What does it mean with local variable? Is that a function local variable? Because there’s also that when you declare a function local as static that it is only initialized once, the first time it enters this function.

It also only talks about storage duration with regards to class members, what about it being non instance specific, that’s also a property of static no? Or is that storage duration?

Now what about the case with static and file scope? Are all global variables considered to have static storage duration by default? The following (from section 3.7.1) seems to indicate so:

1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3)

How does static relate to the linkage of a variable?

This whole static keyword is downright confusing, can someone clarify the different uses for it English and also tell me when to initialize a static class member?

9 Answers
9

Leave a Comment