How does the static life time work?

13

I just saw a question about C. In it the following code was shown:

#include <stdio.h>

int main() {
    static int a = 5;
    printf("%d", a--);
    if(a)
        main();    
    return 0;
}

Example running on repl.it.

And the challenge was to respond to what behavior this code would have (compiled using GCC).

I thought, "infinite loop." So I went to test and I saw that this is not it, the variable a is not assigned to 5 whenever the main method is called. Actually, execution shows 54321 on screen and is finished.

What is the reason for this behavior?

    
asked by anonymous 31.08.2017 / 17:42

1 answer

15

First understand difference between scope and lifetime (the original question was in scope).

There are two types of static variables in C, one is the local scope, the other is the one with the scope of the code file where it is accessed by any function of this file, as if it were a static member class variable.

The lifetime of both is the same as the lifetime of the application, after all the variable is static. This does not change with respect to C # for example, the difference is that C # does not yet have a local static variable.

So the only difference in this variable is that its visibility is more restricted, it can only be accessed in the very function that was declared. The state of it is global, the visibility is that it is local. So it retains the value and each execution will access the global value of it, it is not lost at the end of the function execution.

The global memory area of this variable is only initialized if the function is executed. Initialization will occur only once.

In the comments we spoke about intuitiveness. There is a lot of thing that is intuitive only when you have learned something before, because without prior knowledge the person does not even know where to start. On the other hand, when a person learns something if they see something different from what they tend to think is not intuitive. If you think well the syntax indicates well that, the variable is inside the function and is local, very intuitive, has a word saying that it is static, so it has a life span throughout the application, intuitive as long as you understand the concept of scope and life span. If you do not understand this, other forms can get confusing as well.

Related: Variable static and #define .

    
31.08.2017 / 17:52