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?
Example:
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.