tags:

views:

82

answers:

2

I wanted to know if that has any ill effects under any circumsatnce.

For ex:

Ex1:
void* func1()
{
   void* p_ref = NULL;
   //function scope static variable
   static int var1 = 2;
   p_ref = &var1;
   return p_ref;
}
Ex2:

//file scope static variable
static int var2 = 2;

void* func2()
{
   void* p_ref = NULL;
   var2 = 3;
   p_ref = &var2;
   return p_ref;
}

So in the above two cases what is the difference apart from the fact that var1 is function scope and var2 is file scope.

Thanks in advance.

+4  A: 

I don't believe there is any difference. They're both global variables, it's just that the name of the first one is only visible inside the scope of the function func1.

joefis
One difference between your two functions is that func2 will set the value of the global variable var2 to 3 every time it is called. Whereas func1 will not change the value of var1.
joefis
+1  A: 

Essentially no difference apart from scope.

Hence, local variable is preferable if that pointer is going to be the only way to access the variable.

Marco
Note, though, that function-level static variables tend to make your code non-reentrant, if you rely on (or especially if you change) the value outside the function. Don't do it if you value your sanity.
cHao
@cHao: In this respect too, they are no different to global-scope static variables.
caf
@caf: Right...globals of any type will likely cause reentrancy issues. Function-level statics are particularly insidious, though, partly because at first glance they don't *look* like globals -- even though in every sense that really matters, they are.
cHao