In your recursive call, printf() is executed when main() returned. And since var is a static variable , its value remains 0 (last value = 0 for all function calls)
Note if() false when var becomes 0 (the last value after main (); by calling you do not modify the var-notice diagram).
Hope the following diagram will help you understand (read comments):
main() <---------------+ { | static int var=5; | <----"Declared only one/first time with value 5" if(--var) | ---- main(); ---------+ // called if var != 0 | // main called for var = 4, 3, 2, 1 |// recursion stooped |// return with 0 value |// now no operation applied on `var` so it remain 0 +--> printf(" %d ",var); // called when return ed }
The lifetime of a static function until the program terminates (so that the values are not lost), and the scope is inside the function.
14.1.6 Static Variables
The volume of static automatic variables is identical to the volume of automatic variables, that is, local to the block in which it is defined; however, dedicated storage becomes constant for the duration of the program. Static variables can be initialized in their declaration; however, initializers must be constant expressions, and initialization is performed only once at compile time, when memory is allocated for the static variable * .
Second question:
Again, if you use var-- , then your output will be -1 -1 -1 -1 -1 -1 ?
Suppose your condition is var-- and then if() the fist condition checks true or false before decrementing -- . (because in the expression var-- , -- is postfix).
And since if() breaks when var == 0 , then the recursive call stops and the function returns with a reduced value from 0 to -1 . And since var does not change after the return, it means that there will be -1 for everyone.
source share