Recursion Control flow

拜拜、爱过 提交于 2019-12-24 02:20:59

问题


#include<stdio.h>

void printd(int n)
{
    if(n/10)
        printd(n/10);
    putchar(n%10+'0');
}

In the above code consider n as a positive integer and its value be 123.

First time,123 is passed to printd (first printd) Second time,12 is passed to printd (second printd) Third time,1 is passed to printd (third printd) and putchar prints 1

Then after the control flows to second printd,what is the value of n? Since it is an automatic variable it's value of 1 in third printd vanishes once the function ends and gets the value of 12 in second printd.

If so,second printd will again lead to third printd and so....

But the program beautifully prints 123.

Where did my understanding on control flow and values for variables during function invocation went wrong?

FYI,the program is from K&R section 4.10 recursion


回答1:


You are wrong here:

If so,second printd will again lead to third printd

second printd starts from where it stopped, and not from the start of the function printd. So, the putchar is executed in second printd which prints 2 and the same thing happens in the first printd, printing 3.



来源:https://stackoverflow.com/questions/30589132/recursion-control-flow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!