simran dhamija simran dhamija - 3 months ago 6
C Question

Initialization and updation of variable types

I understand that static variables are initialized only once during the lifetime of the program (see here for reference)

For the following piece of code,

int main() {
static int a=2;
printf("%d",a);
a++;
printf("%d",a);
}


How is the static variable modified?

Contrariwise, how are non-static variables updated? more specifically, how is "a" modified in the following peice of code?

int main() {
int a=2;
printf("%d",a);
a++;
printf("%d",a);
}

Answer

in your first example, the static variable has local scope, but has the same lifecycle as a global variable, and initialized once at program startup. You do that when you want to achieve a side effect (something is initialized, global function call counter...: calling the subroutine has an effect even if it returns nothing...)

It has the same address at every call (which means you could return its address and modify it from somewhere).

in your second example, you define an auto variable, allocated and initialized each time. It may have a different address depending on the call chain (in all calls, recursive, threaded, the variable is guaranteed to be unique, and not modifiable by other calls/threads: no edge effect, reetrant)

Won't make much difference on a main(), but if you put that in a subroutine, in the first case, 2 consecutive calls will yield a different result (2,3, then 3,4), whereas in the second case, 2 consecutive calls will yield the same result (2,3 twice)