C Callback Functions

C Callback Functions
C Callback Functions in C language is a function that is passed as an argument to another function, and is called back inside that function.
Callbacks are implemented using function pointers.
Why Callback Functions Are Needed?
Callback functions help in:
Writing generic & reusable code
Implementing event-driven programming
Sorting, searching, filtering
Embedded systems (interrupts)
Operating systems & drivers
Simple Definition
A callback function is a function that is called by another function, not directly by the programmer.
Basic Syntax (Important )
Passing function pointer as argument:
Simple Callback Example (Beginner)
greet()is called insidecallFunction()
Callback with Multiple Operations (Real Example)
- Same function, different behavior
- Very common interview example
Callbacks Using typedef (Cleaner Code)
- Improves readability
- Used in professional projects
Callbacks in Sorting (Like qsort)
compare()is a callback- Used internally by
qsort()
Callback vs Normal Function
| Feature | Normal Function | Callback |
|---|---|---|
| Called by | Programmer | Another function |
| Flexibility | Low | High |
| Reusability | Limited | Excellent |
| Used in | Simple logic | Frameworks, OS, Embedded |
Callback in Embedded Systems (Concept)
Used for:
Interrupt Service Routines (ISR)
Hardware events
Timers
Common Mistakes
- Forgetting function pointer syntax
- Mismatch in return type or parameters
- Calling function instead of passing pointer
Correct:
Wrong:
Interview Questions (Must Prepare)
What is a callback function?
Why callbacks are use?
How callbacks are implement in C?
Callback vs function pointer
Real-life example of callback
qsort()callback explanation
Summary
- Callback functions enable flexible design
- Implemented using function pointers
- Widely used in OS, embedded, libraries
- Very important for TCS, Wipro, Infosys, Capgemini
