C語言中函式間如何建立通訊?
函式之間透過引數和返回值進行通訊。
C函式的形式如下:
return-datatype function name (argument list){
local variable declarations;
executable statements(s);
return (expression);
}例如,void mul (int x, int y)
{
int p;
p=x*y;
printf("product = %d”,p);
}返回值及其型別
- 函式可以向呼叫函式返回一個值,也可以不返回。
- 這將透過使用return語句完成。
- 返回值型別為void、int、float、char和double。
- 如果函式不返回任何值,則其返回型別為'void'。
函式名
函式必須遵循與C語言中變數名相同的規則。
函式名不能是預定義的函式名。
引數列表
在這個列表中,變數名用逗號隔開。
引數變數從呼叫函式接收值,這為從呼叫函式到被呼叫函式的資料通訊提供了一種手段。
呼叫函式
可以使用語句中的函式名來呼叫函式。
函式定義
每當呼叫函式時,控制權就會轉移到函式定義。
被呼叫函式中的所有語句都稱為函式定義。
函式頭
- 函式定義中的第一行。
實際引數
- 函式呼叫內部的所有變數。
形式引數
函式頭內部的所有變數都稱為形式引數。
示例
以下是C程式中函式間通訊的示例:
#include<stdio.h>
#include<conio.h>
main ( ){
int mul (int, int); // function prototype
int a,b,c;
clrscr( );
printf ("enter 2 numbers”);
scanf("%d %d”, &a, &b);
c = mul (a,b); // function call
printf("product =%d”,c); Actual parameters
getch ( );
}
int mul (int a, int b){ // Formal parameters
//function header
int c;
c = a *b; //Function definition
return c;
}輸出
執行上述程式時,會產生以下結果:
Enter 2 numbers: 10 20 Product = 200
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP