questions about recursion(C language)

2007-04-24 6:25 pm
我想問係一個recursive function入面
我放左個"return"入去
咁係唔係當個function行到return就會做完成個function,唔理之前recursion左幾多次?

e.g
我寫左一段code係咁:
member* search (member* find, char* name){
if(find){
if(strcmp(name,find->name)==0)
return find;
else{
search(find->left_child,name);
search(find->right_brother,name);
}
}
}

我係想用黎係一棵family tree入面
搵番一個岩名個parent
咁樣我呢個function係唔係一搵到岩名就會return個岩名既member既prointer, 而唔繼續搵落去?
thx
更新1:

咁我係唔係應該要加一句 member *tmp; tmp = (member*)malloc(sizeof(member)); 一話唔要malloc?

回答 (1)

2007-04-24 9:59 pm
✔ 最佳答案
Yes, you should return the result when you can find the right name, but in your program, you have not return the result from recursion, you should have like:

member* search (member* find, char* name){
....
else {
member* tmp = search(find->left_child,name);
if (tmp != NULL) tmp = search(find->right_brother,name);
return tmp;
}
.....

Yet the function will stop when return statement is reached, but it will return to the upper level of recursion function and continue the upper level.
e.g.
search(a, b) {
....
search(c,d);
....
}
when search(c,d) ends, the control will pass to search(a,b) and continue.

P.S.: C cannot stop the whole recursion at once, but C++ or JAVA can by applying try-catch clause.


收錄日期: 2021-04-19 23:38:19
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070424000051KK00774

檢視 Wayback Machine 備份