I know that it's a silly question to ask, but please indulge me for a bit.
What do I know?
Scope of a variable
xis basically the block within whichxwas defined. Ifxbelongs to the automatic storage class then, it can only be used within the block where it was declared (which is precisely the scope ofx).Lifetime of a variable
xis basically the time period during whichxis allowed to live in the memory. And ifxis an automatic variable then, by default it'll be killed as soon as it's scope is executed.
So, why do I have this question? It is because of the following code I accidentally conjured.
#include<stdio.h> void scratch(void); int main(void) { for(int i = 0; i < 5; i++) scratch(); return 0; } void scratch(void) { static int static_var = 0; int auto_var1, auto_var2 = 0; printf("[info] 'static' variable = %d | 'auto' variable 1 = %d | 'auto' variable 2 = %d\n", static_var++, auto_var1++, auto_var2); } Output:
[info] 'static' variable = 0 | 'auto' variable 1 = 0 | 'auto' variable 2 = 0 [info] 'static' variable = 1 | 'auto' variable 1 = 1 | 'auto' variable 2 = 0 [info] 'static' variable = 2 | 'auto' variable 1 = 2 | 'auto' variable 2 = 0 [info] 'static' variable = 3 | 'auto' variable 1 = 3 | 'auto' variable 2 = 0 [info] 'static' variable = 4 | 'auto' variable 1 = 4 | 'auto' variable 2 = 0 The static variable, static_var does it's job perfectly well. However, notice the behavior of both automatic variables : auto_var1 & auto_var2. According to my understanding of automatic variables, both auto_var1 & auto_var2 should have printed 0 in each iteration, because their lifetime should have ended the moment scratch() returned to main(). But looks like these guys are living a long life. So my question is why? Does this mean that an automatic variable also has a lifetime equal to that of static variable in the same block? OR is it a compiler based issue?
Note : The above code was compiled via gcc version 7.2.0 on Ubuntu 17. Also, a request to everyone who attempts to answer this question : kindly stick to C for answering.
auto_var1is indeterminate, and using an indeterminate value results in undefined behaviour in C.