Recursion in C, understand recursion example

后端 未结 6 1416
轮回少年
轮回少年 2021-01-27 20:30

i am having trouble understanding this example. I cant figure out what actually happens after a certain point.

Here is the code, the result is supposed to be 4.

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-27 21:06

    You should look at how the calls are chained. Debug output helps:

    int recursion(int i) 
    { 
       int result;
       printf( "called with i=%d\n", i );
       result = (i>1 ? i - recursion(i/2) : 3);
       printf( "call with i=%d will return %d\n", i, result );
       return result;
    } 
    

    The basic idea is that when a recursive call is done the original call is suspended until the recursive one ends.

提交回复
热议问题