0

It would be a mess if we keep using repetitive calling like this :)

int fun() 
{
    static int num = 16;
    return num--;
}

int main()
{
    for (fun(); fun(); fun())
    printf("%d ", fun());
    return 0;
}

I know the concept of Static but I would like to know how this program works and prints output : 14 11 8 5 2

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 11
    There is no recursion in your program. – Mat Aug 02 '17 at 09:16
  • 3
    In order for your program to have recursion you need to have a function that calls itself. – JFMR Aug 02 '17 at 09:17
  • 1
    There is no *stack* in C. If we assume an implementation using a *stack* for function calls, it's still uninteresting: there's just one function called repeatedly. Voting to close this as "unclear what you're asking" (but you might want to clarify). –  Aug 02 '17 at 09:22

1 Answers1

3

First of all, there is no recursion in your program because there is no function at all that calls itself: neither func() calls func() nor main() calls main().


Since the variable num in the function func() is declared as static, all the calls to the function func() share a single copy of the variable num. This variable is initialized only once: the first time the function func() gets called. Its value is kept between calls (this variable is not allocated on the stack).

In the following loop:

for (fun(); fun(); fun())
   printf("%d ", fun());

func() is called once at the very beginning and 3 times on every loop iteration.

Every time func() gets called, num is decremented by one. For that reason, each time the value returned by func() is displayed it is decremented by three with respect to the last displayed value.

JFMR
  • 23,265
  • 4
  • 52
  • 76