C Function Pointer

C Tutorial

🔗 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)

return_type (*pointer_name)(parameter_list);

Example

int (*fp)(int, int);

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)

void process(void (*func)(void *), void *data) {
func(data);
}

✔ 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

int *fp(); // function returning pointer ❌

✔ Correct

int (*fp)(); // pointer to function ✅

❌ Passing function call instead of pointer

process(add()); ❌
process(add); ✅

🔟 Real-Life Use Cases

  • Callbacks & event handling

  • qsort() comparison

  • Device drivers

  • Embedded interrupts

  • Plugin systems


📌 Interview Questions (Must Prepare)

  1. What is function pointer?

  2. Why parentheses are required?

  3. Difference between function pointer & normal pointer

  4. Array of function pointers example

  5. How callbacks are implemented?


✅ Summary

✔ Function pointers store function addresses
✔ Essential for callbacks
✔ Used in system-level programming
✔ Very important for placements & interviews

You may also like...