C Callback Functions

C Tutorial

 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 inside callFunction()

 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

FeatureNormal FunctionCallback
Called byProgrammerAnother function
FlexibilityLowHigh
ReusabilityLimitedExcellent
Used inSimple logicFrameworks, 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)

  1. What is a callback function?

  2. Why callbacks are use?

  3. How callbacks are implement in C?

  4. Callback vs function pointer

  5. Real-life example of callback

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

You may also like...