首頁  >  文章  >  後端開發  >  在C語言中,巢狀函數

在C語言中,巢狀函數

WBOY
WBOY轉載
2023-09-06 13:57:061146瀏覽

在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&#39;

但是GNU C編譯器的擴充功能允許宣告巢狀函數。為此,我們必須在巢狀函數的聲明之前添加auto關鍵字。

範例

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

輸出

my_fun function
Main Function
Done

以上是在C語言中,巢狀函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除