C 語言中的巢狀函式


在某些應用程式中,我們看到一些函式宣告在另一個函式內部。這有時稱為巢狀函式,但實際上這不是巢狀函式。這稱為詞法作用域。詞法作用域在 C 中無效,因為編譯器無法訪問內部函式的正確記憶體位置。

巢狀函式定義不能訪問周圍塊的區域性變數。它們只能訪問全域性變數。在 C 中有兩個巢狀範圍:區域性範圍和全域性範圍。所以巢狀函式有一些有限的用法。如果我們想建立如下形式的巢狀函式,將會生成錯誤。

示例

#include <stdio.h>
main(void) {
   printf("Main Function");
   int my_fun() {
      printf("my_fun function");
      // defining another function inside the first function.
      int my_fun2() {
         printf("my_fun2 is inner function");
      }
   }
   my_fun2();
}

輸出

text.c:(.text+0x1a): undefined reference to `my_fun2'

但是,GNU C 編譯器的擴充套件允許宣告巢狀函式。為此,我們必須在宣告巢狀函式之前新增 auto 關鍵字。

示例

#include <stdio.h>
main(void) {
   auto int my_fun();
   my_fun();
   printf("Main Function
");    int my_fun() {       printf("my_fun function
");    }    printf("Done"); }

輸出

my_fun function
Main Function
Done

更新於: 30-7-2019

4 千+ 瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.