C/C++ 中的函式 (3.5)
函式就像一臺機器,它們執行某些功能併產生某種型別的結果。例如,機器接收一些輸入,處理這些輸入併產生輸出,類似地,函式接收一些值,對這些值進行操作併產生輸出。手動地,一個人將輸入傳遞給機器,然後機器才會開始其功能,以相同的方式,當程式設計師呼叫函式時,它將開始執行。
函式在不同的語言中名稱可能不同,但它們共享兩個共同的特徵,例如:
它們包含需要處理的指令序列
這些指令由一個名稱標識,該名稱指的是函式
為什麼要使用函式?
可重用性 - 當在多個地方需要相同的功能時,最佳方法是建立一次函式並多次呼叫它,而不是一遍又一遍地宣告提供相同功能的函式。可重用性是函式提供的最大功能或優勢。
程式碼模組化 - 函式使您的編碼簡潔明瞭,因為與其在 main() 函式中編寫多行程式碼,不如宣告函式使其更清晰易於閱讀和編寫程式碼。
易於修改 - 如果將來對程式碼有任何更改,那麼程式設計師只需更改函式中的內容,而不是在多個地方進行更改。因此,我們可以說函式還可以減少資料冗餘。
提供抽象 - 透過相關的函式名稱,可以確定該函式應該做什麼,而不是揭示該函式是如何做到的。例如,在 C 中,我們有“maths.h”標頭檔案,其中包含多個函式,包括 pow() 函式。我們可以直接使用此函式來計算冪值,而不必知道此函式在定義中是如何計算它的。
函式宣告和定義
函式宣告是告訴編譯器函式的返回型別和名稱的過程。
語法
無函式體
Return_type function_name(parameter list which is optional);
有函式體
Return_type function_name(parameter list which is optional)
{
//body of the function
} 解釋
return_type - 它告訴編譯器函式是否會返回任何內容,如果返回任何資料,則它將返回什麼型別的資料。
void dummy(){
//since the return type of function is void it willn’t return anything to the caller and hence it willn’t contain return statement.
}
Int dummy(){
//since the return type of function is int it will return integer value to the caller and it is mandatory that it will contain return statement as it is returning integer value.
return integer_value;
}
float dummy(){
//since the return type of function is float it will return floating value to the caller and it is mandatory that it will contain return statement as it is returning floating value.
return float_value;
}
函式名 - 函式名可以是程式設計師想要賦予函式的任何名稱。例如,在上面的示例中,我們將函式命名為 dummy
引數列表(可選) - 每當函式對函式呼叫者傳遞的值進行操作時,都需要建立引數。
函式定義包含函式在被呼叫時應該執行的功能。
示例
#include<iostream>
using namespace std;
//function that calculates the greatest
//value amongst two parameters
int greatest(int val_1, int val_2) //return type of function is integer value{
//body of the function(Definition)
if(val_1>val_2){
return val_1;
}
else{
return val_2;
}
}
int main(){
int val_1=10, val_2=20;
//calling the function and storing the integer value
//returned by a function in the integer variable
int highest = greatest(val_1,val_2);
//printing the greatest value
cout<<"The greatest value is : "<<highest;
//as the return type of main is int,
//it must have return statement for the compiler
return 0;
} 輸出
上面程式碼的輸出將是:
The greatest value is : 20
函式引數
引數是可選的,如果沒有引數,函式也會執行其功能
在函式定義中宣告的變數,用於捕獲函式呼叫者傳遞的值,稱為引數。int greatest(int val_1, int val_2)
int greatest(int val_1, int val_2)

由函式呼叫者傳遞的變數稱為引數。
int highest = greatest(val_1,val_2);

實際引數與形式引數
實際引數是傳遞給函式的資料,例如在上面的示例中,10 和 20 是實際引數
形式引數是函式接收的資料,例如在上面的示例中,val_1 和 val_2 是形式引數。
關於函式 main() 的重要事項
每個程式都有一個入口點,從該點開始執行,例如在 C 和 C++ 中,我們有函式 main()。
如果 main() 函式的返回型別為 void,則表示該函式不會向編譯器返回任何內容,而如果函式 main() 的返回型別為 int,則它會向編譯器返回值。例如,我們在 main() 中有“return 0”,表示程式的終止。
在 C 中 - 函式 main() 的返回型別只能是 void 和 int,因為 main() 函式可以向編譯器返回整數值,也可以不返回任何內容。
在 C++ 中 - 函式 main() 的返回型別只能是 int,因為 main() 函式向編譯器返回值。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP