C Function Pointer
🔗 C Function Pointer
A function pointer in C language stores the address of a function and allows you to call a function indirectly.
👉 Function pointers are the foundation of:
-
Callback functions
-
Dynamic behavior
-
Embedded systems
-
Operating systems
-
Standard library functions (like
qsort)
1️⃣ Why Function Pointers Are Needed?
✔ Dynamic function calling
✔ Code flexibility & reusability
✔ Callbacks implementation
✔ Table-driven programming
2️⃣ Basic Syntax ⭐ (Most Important)
Example
✔ fp can point to any function returning int and taking two int arguments.
3️⃣ Simple Function Pointer Example (Beginner)
📌 fp(5,3) is same as add(5,3)
4️⃣ Function Pointer with typedef (Clean Code ⭐)
✔ Highly used in real projects
✔ Makes code readable
5️⃣ Passing Function Pointer as Argument (Callback)
🔥 This is callback mechanism
6️⃣ Array of Function Pointers 🔥 (Interview Favorite)
✔ Used in menu-driven programs
✔ Used in compilers & OS
7️⃣ Function Pointer with void * (Advanced)
✔ Generic programming
✔ Library-level code
8️⃣ Function Pointer vs Normal Pointer
| Feature | Data Pointer | Function Pointer |
|---|---|---|
| Points to | Variable | Function |
| Syntax | int *p |
int (*fp)() |
| Used for | Data access | Code execution |
9️⃣ Common Mistakes ❌
❌ Wrong parentheses
✔ Correct
❌ Passing function call instead of pointer
🔟 Real-Life Use Cases
-
Callbacks & event handling
-
qsort()comparison -
Device drivers
-
Embedded interrupts
-
Plugin systems
📌 Interview Questions (Must Prepare)
-
What is function pointer?
-
Why parentheses are required?
-
Difference between function pointer & normal pointer
-
Array of function pointers example
-
How callbacks are implemented?
✅ Summary
✔ Function pointers store function addresses
✔ Essential for callbacks
✔ Used in system-level programming
✔ Very important for placements & interviews
