C Callback Functions

1. What is a Callback Function?

  • A callback function is a function passed as an argument to another function.

  • The receiving function can call the passed function at a specific point.

  • Enables dynamic behavior and is widely used in:

    • Event handling

    • Sorting/comparison functions

    • Library APIs


2. How Callback Functions Work

  1. Define a function that performs a task.

  2. Define another function that accepts a function pointer as a parameter.

  3. Pass the function pointer to the second function.

  4. Call the function via the pointer inside the second function.


3. Basic Example: Using a Callback Function

#include <stdio.h>

// Callback function
void greetUser(char name[]) {
printf(“Hello, %s!\n”, name);
}

// Function that accepts a callback
void processName(void (*callback)(char[]), char name[]) {
printf(“Processing name…\n”);
callback(name); // call the passed function
}

int main() {
processName(greetUser, “Alice”);
return 0;
}

Output:

Processing name...
Hello, Alice!

greetUser is passed as a callback to processName.


4. Example: Using Callback with Sorting (Comparison Function)

  • The C library function qsort() uses a callback function for comparison.

#include <stdio.h>
#include <stdlib.h>
// Comparison function
int compare(const void *a, const void *b) {
return (*(int*)a – *(int*)b);
}

int main() {
int arr[] = {5, 2, 8, 3, 1};
int n = sizeof(arr)/sizeof(arr[0]);

qsort(arr, n, sizeof(int), compare); // compare is callback

printf(“Sorted array: “);
for(int i = 0; i < n; i++)
printf(“%d “, arr[i]);
return 0;
}

Output:

Sorted array: 1 2 3 5 8

The compare function is called by qsort() each time it needs to compare elements.


5. Advantages of Callback Functions

  1. Flexibility: Allows the called function to use different behaviors dynamically.

  2. Modularity: Separates generic functions from specific operations.

  3. Reusability: You can reuse the same function with different callbacks.

  4. Event-driven programming: Useful in GUIs, interrupts, and library APIs.


6. Key Points About Callback Functions

  • A callback is implemented using a function pointer.

  • The function pointer must match the signature of the actual function.

  • Widely used in sorting, searching, event handling, and library functions.

  • Enables higher-order programming in C.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *