函式
出自 cppreference.com
函數是 C 語言的一種建構,它將複合語句(函數體)與一個識別字(函數名稱)關聯起來。每個 C 程式都從 main 函數開始執行,該函數執行完畢後會結束程式,或者調用其他使用者自定義的函數或庫函數。
// function definition. // defines a function with the name "sum" and with the body "{ return x+y; }" int sum(int x, int y) { return x + y; }
函數可以接受零個或多個參數 (parameters),這些參數會由函數調用運算子的引數 (arguments)進行初始化,並可以藉由 return 語句向調用者回傳一個值。
int n = sum(1, 2); // parameters x and y are initialized with the arguments 1 and 2
函數的主體由函數定義提供。每個在表達式中使用(除非是未求值的)非內聯 (inline)(C99 起) 函數,在程式中必須僅定義一次。
C 語言中不存在嵌套函數(除非透過非標準的編譯器擴充功能):每個函數定義都必須出現在檔案作用域,且函數無法存取調用者的區域變數。
int main(void) // the main function definition { int sum(int, int); // function declaration (may appear at any scope) int x = 1; // local variable in main sum(1, 2); // function call // int sum(int a, int b) // error: no nested functions // { // return a + b; // } } int sum(int a, int b) // function definition { // return x + a + b; // error: main's x is not accessible within sum return a + b; }
[編輯] 參閱
- C23 標準 (ISO/IEC 9899:2024)
- 6.7.7.4 函數宣告子(包含原型)(p: 待定)
- 6.9.2 函數定義 (p: 待定)
- C17 標準 (ISO/IEC 9899:2018)
- 6.7.6.3 函數宣告子(包含原型)(p: 96-98)
- 6.9.1 函數定義 (p: 113-115)
- C11 標準 (ISO/IEC 9899:2011)
- 6.7.6.3 函數宣告子(包含原型)(p: 133-136)
- 6.9.1 函數定義 (p: 156-158)
- C99 標準 (ISO/IEC 9899:1999)
- 6.7.5.3 函數宣告子(包含原型)(p: 118-121)
- 6.9.1 函數定義 (p: 141-143)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 3.5.4.3 函數宣告子(包含原型)
- 3.7.1 函數定義
[編輯] 參見
| C++ 文件 關於 宣告函數
|