Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of static variables and functions in global scope

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?

like image 309
org 100h Avatar asked Jan 18 '11 14:01

org 100h


People also ask

Why do we need static variables when we have global variables?

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.

Is static list variable globally scoped?

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.

Can static variable access global functions and data?

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.

What is the static variable in function useful for?

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.


2 Answers

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?

like image 88
Nawaz Avatar answered Oct 22 '22 18:10

Nawaz


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.

like image 25
Benoit Thiery Avatar answered Oct 22 '22 19:10

Benoit Thiery