DekGenius.com
Team LiB   Previous Section   Next Section
static storage class Static storage class specifier

storage-class-specifier := static

The static storage class specifier can be used with objects, functions, and class members. Its purpose varies slightly depending on how you use it:

  • For local objects, static affects the object's lifetime: instead of being constructed anew every time the function is called, a static local object is constructed at most once, and the object retains its value across function calls.

  • A static class member is not tied to a specific object. Instead, it is similar to a global object or function, but in the scope of the class that declares it.

  • For global declarations, using static means the object or function has internal linkage instead of the default external linkage, that is, the object or function is not visible in other source files. This use is deprecated; use anonymous namespaces instead.

Example

struct demo {
  static const int size = 10;
  static void func(  ) {
    return size;
  }
private:
  int data_[size];
};
static int local_data = 10;
static int local_func() { return demo::func(  ); }

See Also

auto, class, extern, namespace, register, type, Chapter 2

    Team LiB   Previous Section   Next Section