Can I use unnamed namespaces instead of static variables inside functions?

232 Views Asked by At

I have browsed all the relevant questions about unnamed namespaces, yet I cannot see if and how they can be used to replace a static variable in this context:

returnType dummyfun () {

    static int staticInt;

    // do something...
};
1

There are 1 best solutions below

1
On

An unnamed namespace cannot be used to replace an internal static variable.

Unnamed namespaces are declared outside of the scope of a function. They are useful to allow access to function and variable names within a translation unit while hiding those same names outside of the translation unit.

An internal static variable is a variable whose name is accessible only within the scope of the function where it is declared and whose extent persists between calls to the function.