Pointer to Function** คือตัวแปรที่เก็บที่อยู่ของฟังก์ชันในหน่วยความจำ ช่วยให้สามารถเรียกฟังก์ชันผ่านพอยน์เตอร์ ส่งฟังก์ชันเป็นอาร์กิวเมนต์ หรือสร้าง Callback ได้
การประกาศ
return_type (*pointer_name)(parameter_types);
ตัวอย่าง
int (*p)(int, int); // p ชี้ไปฟังก์ชันที่รับ int 2 ตัว คืน int
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
p = add; // p ชี้ไป add
p = sub; // p ชี้ไป sub
การเรียกใช้
// ทั้งคู่เทียบเท่ากัน
result = add(5, 3); // เรียกตรง
result = (*p)(5, 3); // เรียกผ่าน pointer (Dereference)
result = p(5, 3); // เรียกผ่าน pointer (Implicit dereference - C99+)
ตัวอย่างที่ 1: เรียกฟังก์ชันผ่าน Pointer
#include <stdio.h>
void display() {
printf("Hello from display()\n");
}
int main() {
void (*p)(); // Pointer to function returning void, no params
p = display;
(*p)(); // เรียกผ่าน pointer
p(); // เรียกแบบ Implicit (C99+)
return 0;
}
ผลลัพธ์
Hello from display() Hello from display()
ตัวอย่างที่ 2: ส่ง Pointer to Function เป็น Argument (Callback)
#include <stdio.h>
void show(int *p) {
(*p)++; // เพิ่มค่าที่ p ชี้อยู่
}
int main() {
int a = 20;
int *ptr = &a;
printf("Before: %d\n", a); // 20
show(ptr);
printf("After: %d\n", a); // 21
return 0;
}
ตัวอย่างที่ 3: ใช้จริง - Function Table (Switch แบบ Pointer)
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int div(int a, int b) { return b ? a / b : 0; }
int main() {
// Array of function pointers
int (*ops[4])(int, int) = {add, sub, mul, div};
char *names[] = {"Add", "Subtract", "Multiply", "Divide"};
int x = 20, y = 10;
int choice;
printf("0:Add 1:Sub 2:Mul 3:Div\nChoice: ");
scanf("%d", &choice);
if(choice >= 0 && choice < 4) {
int result = ops[choice](x, y);
printf("%s: %d %c %d = %d\n", names[choice], x,
"+-*/"[choice], y, result);
}
return 0;
}
การประกาศแบบใช้ typedef (อ่านง่ายขึ้น)
// แบบเก่า
int (*p)(int, int);
// ใช้ typedef
typedef int (*BinaryOp)(int, int);
BinaryOp op = add;
op(5, 3); // 8
การประกาศที่ซับซ้อน (Complex Declarations)
// Pointer to function returning pointer to int
int *(*p)(int);
// Function returning pointer to function
int (*func())(int);
// ใช้ cdecl (อ่านได้): declare p as pointer to function (int) returning pointer to int
สรุปการใช้งานหลัก
- Callback Functions - qsort(), bsearch(), Signal Handlers
- State Machines - Function Table แทน Switch Case
- Plugin Architecture - โหลดฟังก์ชันแบบ Dynamic
- Event Handlers - GUI, Embedded Systems