static variable and pointer to static variables in c/c++

2.5k Views Asked by At

If i have static variable:

static int a;

And I want a pointer to point to this variable, should the pointer look like:

static int* f;
f=&a;

And if I return this f to a function call with an assignment statement to a pointer of type static int* will this variable be accessible in that function?

Also:

int a;
static int* f;
f=&a; // does this mean now a is a static variable and it will be retained until the program ends?
static int b;
int* c;
c=&n; // is this possible? 
1

There are 1 best solutions below

0
On
int a;
static int* f;
f=&a; // does this mean now a is a static variable and it will be retained until the program ends?

"[D]oes this mean now a is a static variable"?

No it does not. The static property only apply to the variable you explicitly define as static. In the example above only f is static. The life-time of a will end when its surrounding scope ends, making any pointer to it invalid at that point.

static int b;
int* c;
c=&n; // is this possible? 

"[I]s this possible?"

Yes that's fine. The life-time of local static variables are the full life-time of the program. And global variables (static or not) also have a life-time of the full program. That means pointers to them will always stay valid.

This storage-class specifier reference might be helpful to read through.