I found Why/when should I declare a variable using static?, but the tags is about objective-c .
I can't make sure is there any difference in usage details between c++ and objective-c when you use static, so when/why should I use static in c++?
I found Why/when should I declare a variable using static?, but the tags is about objective-c .
I can't make sure is there any difference in usage details between c++ and objective-c when you use static, so when/why should I use static in c++?
static
has a couple of independent meanings, depending on context.
void f() { ... }
static void g() { ... }
Here, f
has "external linkage", which means that its name is visible in other translation units. That is, in another source file you could have void f();
and then you could call the function f
.
g
, on the other hand, because it's marked static
, has "internal linkage". You can call it from code in the same source file, but you cannot call it from another source file.
Same for objects:
int i = 3; // external linkage
static int j = 4; // internal linkage
And a small complication: you can define a static object inside a function.
void f() {
static int i = 3;
std::cout << i << '\n';
++i;
}
Here, i
has no linkage. It's only visible inside the function. It gets initialized the first time the function is called (and doesn't get initialized at all if the function isn't called). So the first time that f
is called it will write "3" to the console. On the second call it will write "4", etc. Understanding the behavior of objects with destructors is left as an exercise for the reader.
Inside a class definition it's completely different.
class C {
public:
void f();
static void g();
int i;
static int j;
};
Here, when you call f
you must call it on an object of type C
, and f
can use data members of that object, that is, it can look at and change both i
and j
. When you call g
there is no associated object. It's still a member of C
, so it can look at and change j
, because j
, too, is not associated with any object. There's only one j
, and it's shared by all objects of type C
.