23

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?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
org 100h
  • 233
  • 1
  • 2
  • 4

3 Answers3

20

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?

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 6
    And the latest C++0x draft undeprecates it. – Fred Nurk Jan 18 '11 at 14:53
  • @Fred: amusing, it changed between n3092 and n3225, do you know what motivated this change ? – Matthieu M. Jan 18 '11 at 16:27
  • @Matthieu: that's even more interesting. Can you please tell us what motivated this change? or at least refer us to a link? – Nawaz Jan 18 '11 at 16:29
  • 1
    I could not find anything really relevant, I've asked the question ( http://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more ), let's hope someone on SO knows something about it. – Matthieu M. Jan 18 '11 at 16:41
19

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.

Benoit Thiery
  • 6,325
  • 4
  • 22
  • 28
1

Taking as an example -

// At global scope
int globalVar; // Equivalent to static int globalVar;
               // They share the same scope
               // Static variables are guaranteed to be initialized to zero even though
               //    you don't explicitly initialize them.


// At function/local scope

void foo()
{
    static int staticVar ;  // staticVar retains it's value during various function
                            // function calls to foo();                   
}

They both cease to exist only when the program terminates/exits.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • But does the function scoped static variable get initialized at runtime or only when its scoped function, in this case foo() is ran? – James Kuang May 08 '14 at 19:27
  • @Mahesh Is not globalVar a non static if you don't specify static by default?.I think one can easily extend the non static global variables. – starkk92 Oct 15 '14 at 11:53