Callback Function in C

Hello, aspiring programmers! Today, we're diving into the fascinating world of callback functions in C. As your friendly neighborhood computer science teacher, I'm excited to guide you through this concept. Trust me, once you grasp callbacks, you'll feel like you've unlocked a new superpower in programming!

C - Callback Function

What is a Callback Function?

Let's start with the basics. Imagine you're at a pizza party (because who doesn't love pizza?), and you ask your friend to call you when the pizza arrives. Your friend is essentially performing a callback - they're calling you back when a specific event occurs.

In C programming, a callback function works similarly. It's a function that we pass as an argument to another function. This other function then "calls back" (executes) the passed function when a certain event happens or a task is completed.

Here's a simple structure of a callback function:

void callback_function() {
    // Function body
}

void main_function(void (*callback)()) {
    // Some code
    callback();  // Calling the callback function
    // More code
}

int main() {
    main_function(callback_function);
    return 0;
}

In this example, callback_function is our callback. We pass it to main_function, which then calls it at some point during its execution.

Example of Callback Function in C

Let's look at a more concrete example. We'll create a simple program that uses a callback to print a message after a calculation is done.

#include <stdio.h>

// Our callback function
void print_result(int result) {
    printf("The result is: %d\n", result);
}

// Function that performs calculation and calls the callback
void perform_operation(int a, int b, void (*callback)(int)) {
    int sum = a + b;
    callback(sum);  // Call the callback function with the result
}

int main() {
    perform_operation(5, 3, print_result);
    return 0;
}

In this example:

  1. We define a callback function print_result that takes an integer and prints it.
  2. Our perform_operation function takes two integers and a function pointer as arguments.
  3. Inside perform_operation, we calculate the sum and then call the callback function with this sum.
  4. In main, we call perform_operation with our numbers and the print_result callback.

When you run this program, it will output: "The result is: 8"

Callback Function With Arguments

Callbacks can also take multiple arguments. Let's expand our previous example to include more operations:

#include <stdio.h>

// Callback function with multiple arguments
void print_operation(char operation, int a, int b, int result) {
    printf("%d %c %d = %d\n", a, operation, b, result);
}

// Function that performs calculation and calls the callback
void perform_operation(int a, int b, char op, void (*callback)(char, int, int, int)) {
    int result;
    switch(op) {
        case '+': result = a + b; break;
        case '-': result = a - b; break;
        case '*': result = a * b; break;
        case '/': result = a / b; break;
        default: printf("Invalid operation\n"); return;
    }
    callback(op, a, b, result);
}

int main() {
    perform_operation(5, 3, '+', print_operation);
    perform_operation(10, 4, '-', print_operation);
    perform_operation(7, 2, '*', print_operation);
    perform_operation(20, 5, '/', print_operation);
    return 0;
}

This program will output:

5 + 3 = 8
10 - 4 = 6
7 * 2 = 14
20 / 5 = 4

Here, our callback print_operation takes four arguments: the operation, two operands, and the result. This allows us to create a more flexible and informative output.

Types of Callbacks in C

In C, we can categorize callbacks into two main types:

  1. Synchronous Callbacks: These are executed immediately by the function they are passed to. Our examples above are synchronous callbacks.

  2. Asynchronous Callbacks: These are scheduled to be executed later, often used in event-driven programming or when dealing with I/O operations.

Let's look at a table summarizing these types:

Type Description Use Case Example
Synchronous Executed immediately Simple operations, calculations Our arithmetic operations example
Asynchronous Executed later Event handling, I/O operations File read/write callbacks, GUI event handlers

Here's a simple example of an asynchronous callback using signals in C:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void callback_function(int signum) {
    printf("Received signal %d\n", signum);
}

int main() {
    signal(SIGALRM, callback_function);
    alarm(5);  // Set alarm for 5 seconds

    printf("Waiting for alarm...\n");
    pause();  // Wait for a signal

    return 0;
}

In this example, callback_function is set up as an asynchronous callback that will be called when the SIGALRM signal is received. The alarm(5) function sets a timer for 5 seconds, after which the SIGALRM signal will be sent, triggering our callback.

And there you have it, folks! We've journeyed through the land of callback functions in C. Remember, callbacks are like trusty sidekicks in your programming adventures - they're always there when you need them, ready to spring into action. Keep practicing, and soon you'll be wielding callbacks like a pro!

Credits: Image by storyset