-1

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++?

Point wind
  • 73
  • 5
  • 1
    When you want your object to live throughout the lifetime of your program, when you don't want an instance, when you need a helper function etc, etc. The subject is too broad. – Ron Oct 09 '18 at 13:05
  • 2
    related/dupe: https://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c – NathanOliver Oct 09 '18 at 13:06
  • do you have a concrete case? can you show some code? what I dont really understand about the question is that for most uses of `static` you cannot simply add or remove it without breaking other code or completely changing the meaning of the variable, ie it is a decicion you make beforehand not when the variable is already in place – 463035818_is_not_an_ai Oct 09 '18 at 13:25
  • Possible duplicate of [The static keyword and its various uses in C++](https://stackoverflow.com/questions/15235526/the-static-keyword-and-its-various-uses-in-c) – mkaes Oct 09 '18 at 15:29

1 Answers1

4

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165