In C, static
has two usages:
1, Use static
keyword to limit the var's scope in the translation unit. To make this simple, if you have two files: a.c
, b.c
and you wrote:
static int varA;
in a.c
, then this means varA
could only be used in a.c
, if you want to use varA
in b.c
, you should remove the static
keyword, and add extern int varA;
in b.c
, what people usually do is we create another file called: a.h
, and write extern int varA;
in a.h
, and we simply include "a.h"
in b.c
, so we could write every variable we want to extern in a.h
and use a single include "a.h"
to make these variables or functions legal in other .c
files(i.e. source files)
2, Using static
to define a local variable
in a function, for instance:
int TheFunction()
{
static int var = 0;
return ++var;
}
Because you used the static
keyword on a local variable var
, this variable will not loss when TheFunction()
is returned.
The first time you call TheFunction()
you will get 1
, the second time you call TheFunction()
you will get 2
, and so on.
Next, lets see the usage of static in C++.
Because any C++ complier can complie a C code, so the 2 usages above is also in C++.
another two usages is:
1, static member variable.
2, static member function.
Lets see the code directly:
#include <iostream>
using namespace std;
class Test
{
public:
Test() : m_nNormalVar(0)
{
}
public:
// You need to init this static var outside the class
// using the scope operator:
// int Test::m_nStaticVar = 0;
static int m_nStaticVar;
// You can init this const static var in the class.
const static int m_nConstStaticVar = 10;
// This is just a normal member var
int m_nNormalVar;
};
int Test::m_nStaticVar = 0;
int main(int argc, char *argv[])
{
Test a;
Test b;
a.m_nStaticVar++;
a.m_nNormalVar++;
cout << b.m_nStaticVar << endl;
cout << b.m_nNormalVar << endl;
return 0;
}
a
and b
are objects of class Test
they have the same m_nStaticVar
and the same m_nConstStaticVar
, but they have their own m_nNormalVar
this is a static member variable.
#include <iostream>
using namespace std;
class Utility
{
public:
// This is a static member function, you don't
// need to have a concrete object of this class
// to call this function.
static int SelectMax(int a, int b)
{
return a > b ? a : b;
}
};
int main(int argc, char *argv[])
{
// No objects of class Utility
cout << Utility::SelectMax(2, 1) << endl;
return 0;
}
So this is a static member function of a class in C++.
These four ways of static's usage is all I known, if there are still some other usages, please help to edit this post, thx:)
EDIT:
Add static global function
1, Use static
keyword to limit the function's scope in the translation unit. To make this simple, if you have two files: a.c
, b.c
and you wrote:
static void StaticFunction();
in a.c
, so you can only call StaticFunction()
in a.c
, if you want to call this function in b.c
you should remove the static
keyword and then delcare it before the usage. Or just declare it in a.h
and include "a.h"
in b.c