Are static variables in C redistributed every time a parent function is called?

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

If I call this function several times, does the static variable get reallocated in memory every time the function is called?

If it is redistributed, why is the last value always supported?

Example:

void add()
{
    static int x = 1;
    x++;
    printf("%d\n",x);
}

int main()
{
    add(); // return 2
    add(); // return 3
    add(); // return 4
}
0
source share
6 answers

No - static variables are basically global variables that live in a local namespace.

+13
source

, . , ; .

+4

,

?

, (, , ).

+2

. . , .. , .

+2

C , . . , , .

+1

, , , ( ). ( ) ( malloc).

( ) . , , .

, :

int f(int x){
    return x+1;
}

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

gcc, , , :

error: initializer element is not constant

.

+1
source

Source: https://habr.com/ru/post/1778148/


All Articles