- On the difference between static global and static
Static global has file scope and it can't be accessedoutside of the file. While global has program scope and can be accessed outside of file in which it has been defined using extern keyword.
A program can be spread across two or more files...
so, a global variable can be accessed by all the files..
where as, a static global variable can be accessed only bythe file in which it is declared...static means permanent
and hence the value in static global variable is shared by
all the functions in that file...
- Static class variable
#include
using namespace std;
class shared {
static int a;
int b;
public:
void set(int i, int j) {
a=i;
b=j;
}
void show();
} ;
int shared::a;
void shared::show()
{
cout << "This is static a: " <<>
cout << "\nThis is non-static b: " <<>
cout << "\n"; } int main() { shared x, y; x.set(1, 1); x.show(); y.set(2, 2); y.show(); x.show(); return 0; }
- static variable in a function
#include
int func1(){
static long lfunc=1;
printf("%s : lfunc = %d\n ",__func__,lfunc);
lfunc++;
return 0;
}
int main(){
func1();
func1();
func1();
return 0;
}Output:
make static && ./static
g++ static.cpp -o static
func1 : lfunc = 1
func1 : lfunc = 2
func1 : lfunc = 3
A static method defined in a class does not need an object in order to be called.