4

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.

kp11
  • 2,055
  • 6
  • 22
  • 25

2 Answers2

2

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.

eemz
  • 1,183
  • 6
  • 10
  • 2
    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. – eemz May 26 '10 at 10:34
  • I would say that they both have static storage duration which does not mean they both are global variables. Globals are declared outside functions. – Artur Jan 29 '12 at 10:20
2

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
  • 298
  • 2
  • 7
  • 1
    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 May 26 '10 at 10:17
  • @cHao: In this respect too, they are no different to global-scope static variables. – caf May 26 '10 at 13:35
  • @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 May 26 '10 at 21:49