views:

230

answers:

4

In C static can mean either a local variable or a global function/variable without external linkage. In C++ it can also mean a per-class member variable or member function.

Is there any reference to how it happened that the static keyword that seems totally irrelevant to lack of external linkage is used to denote lack of external linkage?

+7  A: 

Using an already existing keyword has the advantage of not adding a new keyword to the language, which could break existing programs. It can be confusing but it is considered a sort of a "lesser evil".

Francesco
And static has, like lot of C++ keyword, a context-dependant meaning.
Klaim
+4  A: 

I assume that you consider the use of static to define variables who retain their value between function calls to be natural.

Consider the following:

void func() {
    static int x;
}

versus

int x;
void func() {
}

From func's point of view, x behaves the same in either case. The value remains between consecutive calls. The difference between the two is who else can see x. In the first, nobody can. In the second, everybody can.

That concept extends to static variables at the global scope. If you just declare a variable, everybody can see it. But if you declare that variable static, only that file can see it. Obviously, you have to allow for the fact that there's no additional scope to limit the visibility, but the idea is there.

The additional meaning in C++ concerning static members is also directly analogous to the original example. A single variable shared by all instances of the class.

Dennis Zickefoose
I am not at all pleased with my wording here :-/ Basically, what I'm trying to get across is that all three uses essentially result in a global variable that is limited to the current scope.
Dennis Zickefoose
+2  A: 

static is a storage specifier. The word "static" means unchanging. "Storage" refers to where the object is in memory, i.e. its address.

An object with static storage resides at a constant address.

It just so happens that an object with extern storage also has a constant address. Due to the way C and C++ programs are linked, it's a necessity. And because extern happens to be the least surprising behavior, it's also the default.

If you think about it in terms of extern being an extra feature on top of static, I think it makes a bit more sense. It is a bit stupid to declare a function static, since there's no alternative in any fully-compiled language, but the address of a function is static even if it's not externally visible.

The really inconsistent part, then, is that class members which get shared between different compilation units must be declared static, not extern

Potatoswatter
+2  A: 

The C version means "statically linked" outside of a function.

The C++ class version and C inside function versions mean "statically stored", meaning that they are not auto (stack or local) variables or instance variables in classes.

nategoose