如何递归工作用C [英] How Recursion works in C

查看:82
本文介绍了如何递归工作用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C,我阅读递归,但我完全糊涂了。

I am new to C and I'm reading about recursion, but I am totally confused.

在那里我感到困惑的主要部分是东西怎么弄达到退出条件时,放松身心。我想知道在递归值是如何得到推和弹出堆栈。

The main part where I'm getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack.

也可以请人给我递归的diagramatic看法?

Also can anyone please give me a diagramatic view of recursion?

谢谢...

推荐答案

让我们假设一个函数:

int MyFunc(int counter) {
    // check this functions counter value from the stack (most recent push)

    // if counter is 0, we've reached the terminating condition, return it
    if(counter == 0) {
        return counter;
    }
    else {
        // terminating condition not reached, push (counter-1) onto stack and recurse
        int valueToPrint = MyFunc(counter - 1);

        // print out the value returned by the recursive call 
        printf("%d", valueToPrint);

        // return the value that was supplied to use 
        // (usually done via a register I think)
        return counter;
    }
}

int main() {
    // Push 9 onto the stack, we don't care about the return value...
    MyFunc(9);
}

输出是:0123456789

The output is: 0123456789

第一次通过MYFUNC,计数为9.失败终止检查(它不为0),因此递归调用被调用,以(计数器-1),8.6

The first time through MyFunc, count is 9. It fails the terminating check (it is not 0), so the recursive call is invoked, with (counter -1), 8.

这重复,递减每次压入堆栈,直到反== 0,在这一点上的价值,终止条款火灾和函数只是返回计数器(0)的值,通常在一个寄存器。

This repeats, decrementing the value pushed onto the stack each time until counter == 0. At this point, the terminating clause fires and the function simply returns the value of counter (0), usually in a register.

的下一个呼叫堆栈,使用返回的值以打印(0),然后返回供给到它时,它被称为(1)的值。这一过程不断重复:

The next call up the stack, uses the returned value to print (0), then returns the value that was supplied into it when it was called (1). This repeats:

的下一个呼叫堆栈,使用返回的值以打印(1),然后返回供给到它时,它被称为(2)的值。等等,直到你得到顶端。

The next call up the stack, uses the returned value to print (1), then returns the value that was supplied into it when it was called (2). etc, till you get to the top..

所以,如果MYFUNC用3调用时,你会得到的(从堆栈忽略返回地址等)等价的:

So, if MyFunc was invoked with 3, you'd get the equivalent of (ignoring return addresses etc from the stack):

Call MyFunc(3) Stack: [3]
Call MyFunc(2) Stack: [2,3]
Call MyFunc(1) Stack: [1,2,3]
Call MyFunc(0) Stack: [0,1,2,3]
Termination fires (top of stack == 0), return top of stack(0).
// Flow returns to:
MyFunc(1) Stack: [1,2,3]
Print returned value (0)
return current top of stack (1)

// Flow returns to:
MyFunc(2) Stack: [2,3]
Print returned value (1)
return current top of stack (2)

// Flow returns to:
MyFunc(3) Stack: [3]
Print returned value (2)
return current top of stack (3)

// and you're done...

这篇关于如何递归工作用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆