Search code examples
cmemorystaticstatic-variablesstatic-functions

What is the exact reason for the keyword static working differently for variables and functions


If we use static in-front of a variable, it's value remain intact for the entire cycle of the program's execution in between function calls. But if we use static with functions they become local to the file in which they are declared. I know this is the way, but I want to know the reason exactly why? Why does static behave in two ways? I tried net but no luck, please explain me! Also please tell me where in the memory a static function would get stored, I personally thinks it is in stack!


Solution

  • In fact keyword static has the same meaning for functions and variables when it is used as the specifier of the linkage that is functions and variables in namespaces declared with keyword static have internal linkage.

    From the C++ Standard (3.5 Program and linkage)

    3 A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static

    Static functions are stored the same way as other functions except that their names are not exported as external names.

    This keyword is overloaded for variables. it also denotes static storage duration. It is what you are speaking about in your post.

    From the C++ Standard (3.7.1 Static storage duration)

    1 All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program (3.6.2, 3.6.3).

    3 The keyword static can be used to declare a local variable with static storage duration.

    4 The keyword static applied to a class data member in a class definition gives the data member static storage duration.

    There is a third meaning of the keyword static in C++ relative to members of a class (in C there is no classes so this is not valid for C).

    1 A data or function member of a class may be declared static in a class definition, in which case it is a static member of the class.