Is there a use for flagging a variable as static
, when it lies in the global scope of a .cpp file, not in a function?
Can you use the static keyword for functions as well? If yes, what is their use?
A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.
The static keyword can be used to declare variables and functions at global scope, namespace scope, and class scope. Static variables can also be declared at local scope.
Yes, a static variable is stored just like a global variable. Its value will persist throughout the lifetime of the program. The static keyword also affect the scope of the variable if it's declared outside of a function. The variable cannot be accessed by name from another source file.
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Yes, if you want to declare file-scope variable, then static
keyword is necessary. static
variables declared in one translation unit cannot be referred to from another translation unit.
By the way, use of static
keyword is deprecated in C++03.
The section $7.3.1.1/2 from the C++ Standard (2003) reads,
The use of the static keyword is deprecated when declaring objects in a namespace scope; the unnamed-namespace provides a superior alternative.
C++ prefers unnamed namespace over static
keyword. See this topic:
Superiority of unnamed namespace over static?
In this case, keyword static means the function or variable can only be used by code in the same cpp file. The associated symbol will not be exported and won't be usable by other modules.
This is good practice to avoid name clashing in big software when you know your global functions or variables are not needed in other modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With