函式是與主程式分離的程式碼段,需要時呼叫執行。最簡單函式不帶參數、回傳 void;其他可帶一或多參數並回傳值。函式命名規則同變數。
int multiply(int, int); // 原型宣告:回傳型別、函式名、參數型別
void showResult(int);
int multiply(int firstNumber, int secondNumber) { // 定義
return firstNumber * secondNumber;
}
原型宣告告訴編譯器參數個數、型別與回傳型別,可選擇性包含參數名稱供文件用。定義包含實際函式本體。
函式可傳遞變數、常值、其他函式回傳值:
result = multiply(x, y); // 變數
result = multiply(3, 4); // 常值
result = multiply(getX(), getY()); // 函式回傳值
可忽略回傳值(如 getch()),僅放棄該值無他害。許多函式先執行動作再回傳狀態碼,有時與程式無關可忽略。
函式可呼叫自身,稱為遞迴。這在 C++ 較複雜,此處不展開。
本節介紹獨立函式(非類別成員)。C++ 獨立函式用法同 C,進階特性(如預設參數、多載、內聯)將在後續介紹。
#include <iostream.h>
#include <conio.h>
#pragma hdrstop
int multiply(int, int);
void showResult(int);
int main(int argc, char **argv) {
int x, y, result;
cout << endl << "Enter the first value:";
cin >> x;
cout << "Enter the second value:";
cin >> y;
result = multiply(x, y);
showResult(result);
cout << endl << endl << "Press any key to continue...";
getch();
return 0;
}
int multiply(int a, int b) { return a * b; }
void showResult(int r) { cout << "Result: " << r; }