ฟังก์ชันใน C แบ่งใหญ่ 2 ประเภท:
1. Predefined / Library Functions (ฟังก์ชันไลบรารี)
- กำหนดไว้ใน System Libraries แล้ว
- นำมาใช้งานได้เลย ต้อง Include Header ที่เหมาะสม
- โปรแกรมเมอร์ต้องรู้ Syntax/Parameters
ตัวอย่างยอดนิยม
| Function | Header | Description |
|---|---|---|
| printf() | <stdio.h> | พิมพ์ข้อความจัดรูปแบบ |
| scanf() | <stdio.h> | อ่าน Input จัดรูปแบบ |
| sqrt() | <math.h> | รากที่สอง |
| pow() | <math.h> | ยกกำลัง |
| strlen() | <string.h> | ความยาวสตริง |
| strcpy() | <string.h> | คัดลอกสตริง |
| malloc() | <stdlib.h> | จองหน่วยความจำ Dynamic |
| qsort() | <stdlib.h> | Quick Sort |
ตัวอย่าง: ใช้ sqrt()
#include <stdio.h>
#include <math.h>
int main() {
int x;
printf("Enter positive number: ");
scanf("%d", &x);
double y = sqrt(x);
printf("Square root = %.2f\n", y);
return 0;
}
2. User-defined Functions (ฟังก์ชันที่ผู้ใช้สร้าง)
- โปรแกรมเมอร์เขียนเอง ตามความต้องการ
- ต้อง Define เอง ก่อนใช้ (หรือมี Prototype)
- ไม่ต้อง Include Header เพิ่ม
- ยืดหยุ่น ปรับแต่งได้ตามต้องการ
ตัวอย่าง: ฟังก์ชันคำนวณผลรวม
#include <stdio.h>
// Prototype
int sum(int a, int b);
int main() {
int a, b, c;
printf("Enter 2 numbers: ");
scanf("%d %d", &a, &b);
c = sum(a, b); // เรียกใช้
printf("Sum = %d\n", c);
return 0;
}
// Definition
int sum(int a, int b) {
return a + b;
}
ผลลัพธ์
Enter 2 numbers: 10 20 Sum = 30
เปรียบเทียบ
| ลักษณะ | Library Functions | User-defined Functions |
|---|---|---|
| ผู้สร้าง | Compiler/Standard Library | Programmer |
| Header ที่ต้อง Include | ต้อง Include | ไม่ต้อง (แต่ควรมี Prototype) |
| การแก้ไข | ไม่ได้ (Standard) | ได้ตามต้องการ |
| Portability | สูง (ANSI C) | ขึ้นกับการเขียน |
| Performance | Optimized | ขึ้นกับการ Implement |
แนวทาง: สร้าง Library เอง
รวม User-defined Functions ที่ใช้บ่อยเป็น Header File (.h) และ Source File (.c) เพื่อนำกลับมาใช้ซ้ำได้
// mymath.h
#ifndef MYMATH_H
#define MYMATH_H
int add(int a, int b);
int max(int a, int b);
#endif
// mymath.c
#include "mymath.h"
int add(int a, int b) { return a + b; }
int max(int a, int b) { return (a > b) ? a : b; }
// main.c
#include <stdio.h>
#include "mymath.h"
int main() {
printf("Max: %d\n", max(10, 20));
return 0;
}