return函数如何将值返回到If语句?

时间:2014-07-20 11:42:53

标签: c return function-calls

如何将值1传递给main函数中的if语句,以及return函数如何与其中的递归调用一起工作?

#include <stdio.h>
#include <stdlib.h>
 int identicalTrees(struct node* a, struct node* b)
  {
if (a==NULL && b==NULL)
    return 1;

if (a!=NULL && b!=NULL)
{
    return
    (
        a->data == b->data &&
        identicalTrees(a->left, b->left) &&
        identicalTrees(a->right, b->right)
    );
}

return 0;
} 




 int main()
{
if(identicalTrees(root1, root2))
    printf("Both tree are identical.");
else
    printf("Trees are not identical.");

getchar();
 return 0;
}

1 个答案:

答案 0 :(得分:4)

当调用已声明为返回值的方法时,每次调用该方法时,都会在堆栈上为返回值保留空间。 Return 语句将值放在堆栈上的该位置,并退出返回到调用该方法的代码的方法。调用该方法的代码通过 Return 语句检索放在堆栈上的值,并在 If 语句中使用它。

在递归中,对方法的每次连续调用都将自己的本地堆栈变量空间添加到堆栈顶部。当一个方法执行时,堆栈指针的当前顶部递减为“释放”该方法的堆栈空间。

有关详细说明,请参阅http://en.wikipedia.org/wiki/Stack-oriented_programming_languagehttp://en.wikipedia.org/wiki/Recursion_(computer_science)以及https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html