在這種情況下,調用fun()就像調用任何其他函數一樣。例如:
int main() {
int a = 0;
foo(a);
printf("main a = %d\n", a);
}
void foo(int a) {
a = 1;
bar(a);
printf("foo a = %d\n", a);
}
void bar(int a) {
a = 2;
printf("bar a = %d\n", a);
}
您的來電順序是這樣的:
main();
foo();
bar();
而你的輸出將是這樣的:
bar a = 2
foo a = 1
main a = 0
的參數是按值傳遞的,所以a
是抄並且在每個函數中實際上是一個不同的變量。遞歸也一樣。
main(); x = 3
fun(3); a = 3, so a > 0, nothing happens, return to main()
如果你要改變的條件很有趣()調用自身時,> 0(讀自上而下)
main(); x = 3
fun(3); a = 3, a > 0 so --a = 2, fun(2)
fun(2); a = 2, a > 0 so --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0) /* same as fun(1) above */
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2) /* same as fun(1) above */
fun(2); printf("%d", a) displays 2, --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0) /* this is a new fun(1) */
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); nothing left to do so return to fun(3)
fun(3); printf("%d", a) displays 3, --a = 2, fun(2) /* halfway point */
fun(2); a = 2, a > 0 so --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); printf("%d", a) displays 2, --a = 1, fun(1)
fun(1); a = 1, a > 0 so --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); printf("%d", a) displays 1, --a = 0, fun(0)
fun(0); a = 0, so return to fun(1)
fun(1); nothing left to do so return to fun(2)
fun(2); nothing left to do so return to fun(3)
fun(3); nothing left to do so return to main()
和你的輸出應該是:1213121反映的樹結構電話:
3
/\
/ \
2 2
/\ /\
1 1 1 1
目前看來它什麼也沒做。如果它傳遞一個正值,則不會發生任何事情,而負值將進入無限遞歸。另外,你的函數沒有返回類型。 – 2012-08-01 12:40:04
爲了理解遞歸,你必須先理解遞歸。 – 2012-08-01 12:40:23
由於第一次調用的值小於0,所以'if'條件被評估爲False,並且沒有任何反應。我認爲正確的條件應該是:'if(a> 0)'。 – danihp 2012-08-01 12:41:10