C語言允許函數調用它自己,這種調用的過程稱為“遞歸(recursion)”
舉例說明,如下代碼:
#include <stdio.h> void up_and_down(int); int main(void) { up_and_down(1); return 0; } void up_and_down(int n) { printf("Level %d: n location %p\n",n,&n); if (n < 3) up_and_down(n+1); printf("LEVEL %d: n location %p\n",n,&n); }
定義一個函數up_and_down(int n),且函數當中再次調用本身。下面是程序運行效果:
[root@MiWiFi-R4-srv C]# cc recur.c
[root@MiWiFi-R4-srv C]# ./a.out
Level 1: n location 0x7ffdbc113dac
Level 2: n location 0x7ffdbc113d8c
Level 3: n location 0x7ffdbc113d6c
LEVEL 3: n location 0x7ffdbc113d6c
LEVEL 2: n location 0x7ffdbc113d8c
LEVEL 1: n location 0x7ffdbc113dac
代碼分析;函數up_and_down(int n)中在包含if語句,符合條件變再次調用自身,那么可將up_and_down(int n)分解寫成如下形式:
void up_and_down(int n) //根據主函數賦值,n=1; {
printf("Level %d: n location %p\n",n,&n);
//輸出顯示:Level 1 :n ............. if (n < 3) //判定n=1,且小於3;則進入if語句。 { n = n + 1; //在if語句中,n被重新賦值,且值為2。 printf("Level %d: n location %p\n",n,&n);
//輸出顯示:Level 2 :n ............. if (n < 3) //再次遇到if語句,n等於2,條件語句為真,則執行if語句。 { n = n + 1; //n被重新賦值,且值為3。 printf("Level %d: n location %p\n",n,&n);
//輸出顯示:Level 3 :n ........... if(n < 3) //執行判定語句,條件語句為假,則跳過if語句。 up_and_down(n+1); printf("LEVEL %d: n location %p\n",n,&n); //執行語句,輸出顯示:LEVEL 3 :n ......... } printf("LEVEL %d: n location %p\n",n,&n); //執行語句,輸出顯示:LEVEL 2 :n ............ } printf("LEVEL %d: n location %p\n",n,&n); //執行語句,輸出顯示:LEVEL 1 :n ........ }
分析代碼行為如下。
1;n 接收到主函數值為1,運行printf()函數,之后判定if語句,條件為真則繼續調用本身,執行printf()函數,判定if語句。直到if條件為假,停止調用本身。
2;當 n 的值為3 時。if條件語句為假,則跳過if語句,執行printf("LEVEL %d: n location %p\n", n , &n);(注意:此時n的值為3).
3;當遞歸函數(n值為3時)執行結束,則將控制權返回給上一級遞歸(n的值為2)的時候,繼續完成遞歸函數。重復行為,直到返回到主函數,即n的值為1的時候。