ฟังก์ชันเป็นบล็อกอิสระที่ทำงานเฉพาะเจาะจง
ประเภทของฟังก์ชัน
แบ่งได้ 2 ประเภทหลัก:
- ฟังก์ชันสำเร็จรูป (Predefined functions)
- ฟังก์ชันผู้ใช้กำหนด (User defined functions)
การสื่อสารระหว่างฟังก์ชัน
ฟังก์ชันสื่อสารผ่าน arguments และ return value
รูปแบบฟังก์ชัน C:
{ local variable declarations; executable statements(s); return (expression); }
ตัวอย่าง: void mul (int x, int y)
{ int p; p=x*y; printf(“product = %d”,p); }
Function Prototype (ต้นแบบฟังก์ชัน)
ทำได้ 2 วิธี:
สร้างสำเนาการประกาศฟังก์ชันพร้อมชนิดอาร์กิวเมนต์ พร้อมหรือไม่มี identifier
int func(int, float, unsigned [2]); int func(int i, float f, unsigned u[2]);
เขียน function definition ในรูปแบบ prototype
int func(int i, float f, unsigned u[2]){ < code for func > }
ประโยชน์ของ Function Prototype
ตรวจสอบการเรียกฟังก์ชันด้วยอาร์กิวเมนต์ชนิดไม่ตรง
เมื่อพบการประกาศซ้ำ (explicit/implicit) คอมไพเลอร์จะตรวจสอบความสอดคล้อง