c - 解释一下下面代码的输出?

标签 c recursion

void count(int n){
    static int d=1;
    printf("%d",n);
    printf("%d",d);
    d++;
    if(n>1) count(n-1);
    printf("%d",d);
}
int main(){
    count(3);
}

我是编程新手,所以请帮助我理解,为什么即使在“if”语句为假之后输出还包含两个4,并且此后函数没有递归调用?

最佳答案

这是因为函数末尾的printf("%d",d);

并且该语句被执行n次。

展开count(3)的递归调用,我们得到。

3
1
count(2)
d

进一步展开,我们得到。

3
1
   2
   2
   count(1)
   d
d

再次展开我们得到,

3
1
   2
   2
       1
       3
           ... recursion ends here
       d
   d
d

关于c - 解释一下下面代码的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40176351/

相关文章:

objective-c - 如何在 Interface Builder 中使用结构中的值

iphone - Xcode中如何编译第三方c库?

linux - Glob 是不同的值错误打开文件和读取

python - 如何获取 Python 递归中使用的堆栈帧总数?

scala - scala 中的递归排序与尾递归

无法运行 make 创建的可执行文件

编译的 c 脚本只保持打开状态几分之一秒

javascript - TypeScript 中的异步/等待递归树遍历

c - 文件 I/O 代码中的指针声明

Php 按值传递对象