Skip to content

[C 語言] 函式(Functions)

函式function)是程式設計中的一個重要的概念,函式並不是公式,而是完成特定功能的程式碼區塊。一般而言,『函式』跟『函數』有點像:我們輸入 INPUT,就會產生執行後的結果 OUTPUT。

c_function

而使用函式的優點在於,若我們要實現的功能會反覆使用,那麼這段程式碼只要寫成函式一次即可,接著若有需要反覆使用,則呼叫此函式。

除此之外,將不同功能分成不同的函式,甚至還能提升程式碼可讀性,讓架構更清晰。


範例程式碼

函式宣告的格式通常為:

返回的資料型態 函式名稱(參數資料型態 參數_1, ...) {
    程式敘述;
    ...
    return 返回結果;
}

以下,則是一段計算數值次方的函式。

#include <stdio.h>


// Function
int power(int base, int n) {
    int ans = base;

    for (int i=0; i<n; ++i) {
        ans = ans * base;
    }

    return ans;
}


// Main
int main() {
    // Init
    int base, n, ans;

    // Case 1
    base = 3;
    n = 3;
    ans = power(base, n);
    printf("Case 1: %d^%d=%d\n", base, n, ans);

    // Case 2
    base = 2;
    n = 10;
    ans = power(base, n);
    printf("Case 2: %d^%d=%d\n", base, n, ans);

    return 0;
}


Output:

Case 1: 3^3=81
Case 2: 2^10=2048

References


Read More

Tags:

Leave a Reply