Values obtained in case of a recursive function

In your recursion call printf() executes when main() returns. And because var is a static variable its value remain 0 (last value = 0 same for all function call)

Note if() condition false when var becomes 0 (last value, after main(); call you don’t change var – notice diagram).

Hope following diagram will help you to 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  
}

Remainder life of static function is till program terminates (so values not loss), and Scope is within function.

14.1.6 Static Variables

The scope of static automatic variables is identical to that of
automatic variables, i.e. it is local to the block in which it is
defined; however, the storage allocated becomes permanent for the
duration of the program. Static variables may be initialized in their
declarations; however, the initializers must be constant expressions,
and initialization is done 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 if your condition will be var-- then if() condition fist checks true or false before decrement --. (because in expression var--, -- is postfix).
And because if() breaks when var == 0 then recursive call stops and function returns with decremented value from 0 to -1. And because after return var doesn’t change hence output is -1 for all.

Leave a Comment