What is really happening in this code?

后端 未结 6 469
轮回少年
轮回少年 2020-12-03 16:51

I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn\'t get it really:

#include
void         


        
6条回答
  •  悲&欢浪女
    2020-12-03 17:15

    next time it calls itself it has a smaller value

    count(int m)
    {
     if(m>0)
     count(m-1); // now it is calling the method "count" again, except m is one less
     printf("%d",m);
    }
    

    So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:

    if(m>0)
    

    What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)

    so you have:

    count(int m)
        {
         if(m>0)
         {
             count(m-1); // now it is calling the method "count" again, except m is one less
         }
         printf("%d",m);
        }
    

    So, the recursive calls will stop once m is not > 0, and then it will call the printf.

    After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....

    So the output should be:

    "0 1 2 3 4 5 6 7 8 9 10"
    

    EDIT: In terms of a stack:

    This is what the stack is doing:

    count(10) // push count(10)
    

    ->

    count(9) // push count(9)
    count (10)
    

    ->

    ...

    ->

    count(0) // push count(0)
    count(1)
    count(2)
    count(3)
    count(4)
    count(5)
    count(6)
    count(7)
    count(8)
    count(9)
    count(10)
    

    -> (and then it starts printing and popping the method off the stack)

    // pop count(0), and printf(0)
    count(1)
    count(2)
    count(3)
    count(4)
    count(5)
    count(6)
    count(7)
    count(8)
    count(9)
    count(10)
    

    ->

    // pop count(1), and printf(1)
    count(2)
    count(3)
    count(4)
    count(5)
    count(6)
    count(7)
    count(8)
    count(9)
    count(10)
    

    ->

    ...

    ->

    // pop count(9), and printf(9)
    count(10)
    

    ->

    // pop count(10), and printf(10)
    

提交回复
热议问题