Description
In cpp, the keyword static
is currently used at three different places:
- To declare objects with static lifetime
- To specify global variables with internal linkage
- To declare static members (data and functions) in classes
All of these 3 use cases are very different from one-another and therefore, using same keyword for all of them can be confusing, especially to beginners. Consider the following code:
static int a = 9;
auto foo (char t ){
static float g = 42.0f;
}
The static
in above declarations does different things (yes I know the variables behave kinda same but static
does different things to them).
Therefore, I propose to divide the static
keyword into 3 parts to address each use case differently.
- The first use case is the only one with radical change. Instead of using keyword
static
, we could agree on some different keyword that captures intent clearly in an unambigious way.
//cpp1 code
static int a = 0;
//cpp2 code
SOMETHING a := 0; //not sure on position of keyword
I think something like global
can be used but put down your suggestions.
-
This use case is already covered by anonymous namespaces in cpp and I think that's how it should be in cpp2. So no change here. Anonymous namespaces are a bit more verbose so if anyone has better idea, do suggest.
-
This use case is partially already covered in cpp2. Static member functions are easily and distinguishably declared in cpp2 without the use of
static
keyword. So I'll be addressing the data member part only. The simple way would be to have a keyword. The real decision to make is whether it would be same as keyword chosen for 1) or a different one. A discussion on this topic would probably be needed so this currently is left unaddressed.
Note: I'd like to expand a bit on 1) to cover global variables too. They also have static lifetime. We can make it mandatory for global variables to be declared with some keyword (same as that would be decided for 1). Herb has plans to make global variables constexpr
by default and is not sure if he'll even allow them or not. Having a keyword will capture attention of programmer and also be consistent with other static lifetime variables that would be declared.
These changes will make different things look different and do away with one small source of confusion to new programmers. This is a very small change so shouldn't be hard to implement.
Alternatives
We could also come up with different syntax for case 3) and leave case 1) as it is. That would be one option.