0

I want to share a variable between all function in my cpp file so I wrote:

static int Graph_Id = 0;

But I have noticed that I could also write:

int Graph_Id = 0;

What is the difference here and which is the correct one?

  • The second is an external variable that can be accessed by other compilation units that you link with this. – Barmar Aug 06 '20 at 16:31
  • I would say neither is correct; unless that global is a constant in some form you're opening up a can of worms by avoiding encapsulation (and oop design). You have classes in C++, you should use them – Rogue Aug 06 '20 at 16:32
  • 1
    The concept you're missing is "translation unit", or "compilation unit". It doesn't matter so long as you only have one. – molbdnilo Aug 06 '20 at 16:33
  • @Rogue That will still require a global class instance to contain the value, unless you want to pass the instance as a parameter to every function. – Barmar Aug 06 '20 at 16:33
  • If you only want to use Graph_Id within the one C++ source file, then the first one is the better choice. If you need to access Graph_Id across several C++ source files, then the second one is the only choice (and you should have `extern int Graph_Id;` in an appropriate header file). – Eljay Aug 06 '20 at 16:34
  • Depends on the use case, but here imo since it's named `Graph_Id` I would assume it represents the likely unique ID of _something_, which should be represented as such in the code (rather than as some global that's included all over the place). – Rogue Aug 06 '20 at 16:37

0 Answers0