Internal static variables in C, would you use them?

后端 未结 13 1527
甜味超标
甜味超标 2020-12-07 19:09

In C you can have external static variables that are viewable every where in the file, while internal static variables are only visible in the function but is persistent

13条回答
  •  误落风尘
    2020-12-07 19:44

    For example, in C++, it is used as one way to get singleton istances

    SingletonObject& getInstance()
    {
      static SingletonObject o;
      return o;
    }
    

    which is used to solve the initialization order problem (although it's not thread-safe).

    Ad "shouldn't the function be in its own file"

    Certainly not, that's nonsense. Much of the point of programming languages is to facilitate isolation and therefore reuse of code (local variables, procedures, structures etc. all do that) and this is just another way to do that.

    BTW, as others pointed out, almost every argument against global variables applies to static variables too, because they are in fact globals. But there are many cases when it's ok to use globals, and people do.

提交回复
热议问题