Tutorial :Are static variables in C re-allocated every time the parent function is called?


Suppose I have a static variable declared inside a function in C.

If I call that function multiple times, does the static variable get re-allocated in memory every time the function is called?

If it does get re-allocated, why is the last value always maintained?


void add()  {      static int x = 1;      x++;      printf("%d\n",x);  }    int main()  {      add(); // return 2      add(); // return 3      add(); // return 4  }  


No - static variables are basically globals that live within the local namespace.


No, the variable is not reallocated everytime. It is like having a global variable, but it only has local scope; i.e., you can only reference it from inside of that function.



How else should it retain it's value between function calls?

Static variables are like global variables in this regard, however they are local to the surrounding scope (function, class, namespace).


The static variable is not re-allocated every time the function is called. They act as normal local variables. But they differ in storage duration i.e. when a function assigns some value to the static variables, that value is retained between function calls.


In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.


As the static prefix suggest the variable is in static memory that contains variables whose addresses is known at compile time (a somewhat pedantic way to say with global variables). That different from automatic variables (allocated on the stack) and dynamic variables (allocated on the heap using malloc).

The initialization of static variables in functions (or other static) is performed before the program is run. More precisely it means it can only be some constant expression, that the compiler can get at compile time.

That means the following program is not valid:

int f(int x){      return x+1;  }    int main(){      static int a = f(1);      return a;  }  

When I compile it with gcc it complains as expected with the following message:

error: initializer element is not constant  

However when the program run you can change the value of static variables as any other one.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »