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)


 Why Function Pointers Are Needed?

  •  Dynamic function calling
  •  Code flexibility & reusability
  •  Callbacks implementation
  •  Table-driven programming

Basic Syntax (Most Important)

Example

  • fp can point to any function returning int and taking two int arguments.

 Simple Function Pointer Example (Beginner)


 

  • fp(5,3) is same as add(5,3)

 Function Pointer with typedef (Clean Code)


 

  •  Highly used in real projects
  •  Makes code readable

 Passing Function Pointer as Argument (Callback)


 

  •  This is callback mechanism

 Array of Function Pointers (Interview Favorite)


 

  •  Used in menu-driven programs
  •  Used in compilers & OS

 Function Pointer with void * (Advanced)

  • Generic programming
  •  Library-level code

 Function Pointer vs Normal Pointer

FeatureData PointerFunction Pointer
Points toVariableFunction
Syntaxint *pint (*fp)()
Used forData accessCode execution

 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)

  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...