Callback Function in C Programming

This article is the continuation of the Series on the C programming tutorial and carries the discussion on C language programming and its implementation. It aims to provide easy and practical examples for understanding the C program. In our last article, we have seen the Types of pointers in C programming.

If you are learning or working on any programming language, then someone has for sure asked you to create a callback function. If you are a beginner, then you will get confused what is the callback function and how to create a callback function.

Callback functions are a vital and often critical concept when the developers need to create drivers or custom libraries. This post will help you to understand the callback Function in C.

Callback Function in C with Example?

What is a Callback in real life?

We will take the real scenario. Mr. John is going to the barbershop to trim his beard. There are many customers already waiting. The barber told John, there are few customers before you. I don’t know how long it will take to finish them. Please wait until I finish that.

But Mr. John can’t wait, as he has some other work to do. So, Mr. John decided to give his phone number to the barber and ask him to call back when he finished his work. The barber agreed.

Now, Mr. John can do some other work that he wants rather than waiting simply. The barber finishes his work after an hour. He called him. That’s how callback works in our day-to-day life. We can say many examples like this.

Similarly, there is a callback function in the C programming language too.

What is the Callback Function in C?

In C or any other programming language, we will give the function address to another function or any other code. So, that code can call the function at any time whenever it needs. A callback function is a function that is called by using a function pointer.

The following are some scenarios that help us understand the concept of callback functions in C.

  • Let’s say you are transferring the data using any communication. If you encounter an error, you have to inform the higher layer or upper layer. If you know the upper layer function’s address, then you can directly call that using the callback mechanism.
  • In Embedded Systems, the developer creates a GPIO driver that has an interrupt service routine. When the interrupt fires, the driver has to inform the application layer. The driver doesn’t care about the functionality, but only that at run-time it knows what function should be called when the interrupt fires. The code that will invoke the callback function within the module. This callback mechanism is often called as the signal handler.

Difference between Function Pointer and Callback Function

A function pointer is a pointer that points to the function. Whereas, callback functions are function pointers passed as parameters of the function, which can be called back when an event occurs.

In most instances, a callback will contain three pieces:

  • The callback function
  • A callback registration
  • Callback execution

Callbacks in C – Example Code

The following code will help you to understand the callbacks in C. In the below code, callback_fn is a callback function, and we are registering that callback function in the main function by assigning the callback function’s address (function pointer).

Then we pass the function pointer to the function test_loop. When the value equals 5, we will execute the callback function.

// A simple C program to demonstrate callback mechanism
#include<stdio.h>

// Callback Function which has no argument and no return value
void callback_fn( void )
{
    printf("In callback function\n");
}

void test_loop( void (*fn)(void) )
{
    for( int i = 0; i < 6; i++ )
    {
        if(i == 5)
        {
            // callback execution
            (*fn) ();
        }
        printf("i = %d\n", i);
    }
}
  
int main()
{
    // Registering the callback
    void (*fn_ptr)( void ) = &callback_fn;
      
    // calling the function with the function pointer
    test_loop(fn_ptr);
  
   return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
In callback function
i = 5

If you see the above output, we have called the callback_fn using the function pointer. Some people might ask why we need a function pointer here. Instead, we can directly call  callback_fn itself like the below program.

#include<stdio.h>

void callback_fn( void )
{
    printf("In callback function\n");
}
  
void test_loop( void )
{
    for( int i = 0; i < 6; i++ )
    {
        if(i == 5)
        {
            callback_fn()
        }
        printf("i = %d\n", i);
    }
}
  
int main()
{
    test_loop();
  
    return 0;
}

This program also generates the same output without the callback mechanism. That is awesome doubt.

Here, we just wrote a simple program to explain the callback function. But the actual case won’t be like this. That callback function won’t be present in the same file or library. It will be present in some other library.

So we don’t know the name of the function. So, we will get the address of the function and then just call it. Now you are clear I guess.

You can use typedef for the function pointer, which improves the readability. Refer to the example program below.

#include<stdio.h>

typedef void (*callback_)( void );

// Callback Function which has no argument and no return value
void callback_fn( void )
{
    printf("In callback function\n");
}
void test_loop( callback_ fn )
{
    for( int i = 0; i < 6; i++ )
    {
        if(i == 5)
        {
            // callback execution
            fn();
        }
        printf("i = %d\n", i);
    }
}
  
int main()
{
    // Registering the callback
    callback_  fn_ptr = &callback_fn;
      
    // calling the function with the function pointer
    test_loop(fn_ptr);
  
   return 0;
}

Callback Function in C with Arguments

Code:

The below code demonstrates the callback function with arguments.

#include<stdio.h>

typedef void (*callback_)( int val );

// Callback Function which has no argument and no return value
void callback_fn( int val )
{
    printf("In callback function, val = %d\n", val);
}
void test_loop( callback_ fn )
{
    for( int i = 0; i < 6; i++ )
    {
        if(i == 5)
        {
            // callback execution
            fn( i );
        }
        printf("i = %d\n", i);
    }
}
  
int main()
{
    // Registering the callback
    callback_  fn_ptr = &callback_fn;
      
    // calling the function with the function pointer
    test_loop(fn_ptr);
  
   return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
In callback function, val = 5
i = 5

Advantages of the Callback Function?

Callback functions offer several advantages in the C programming language. Here are some key advantages of using callback functions:

  1. Extensibility: Callback functions provide a way to extend the functionality of a program without modifying its core code. By registering a callback function, you can specify additional behavior to be executed at specific points in the program’s execution.
  2. Flexibility: Callback functions allow for dynamic and runtime decision-making. Instead of having a fixed behavior, a program can determine which function to execute based on certain conditions or events that occur during runtime.
  3. Code Reusability: Callback functions promote code reusability by separating generic functionality (implemented in the main code) from specific functionality (implemented in the callback function). This modularity allows the same callback function to be used in different contexts, reducing code duplication.
  4. Event Handling: Callback functions are commonly used in event-driven programming, where specific events or user actions trigger the execution of code. By registering callback functions for different events, you can define custom actions to be performed when those events occur.
  5. Asynchronous Programming: Callback functions facilitate asynchronous programming, where tasks can be executed in parallel without blocking the main program’s execution. By passing a callback function as an argument to an asynchronous task, the task can notify the program when it is finished or provide intermediate results.
  6. Decoupling: Callback functions help decouple different parts of a system by allowing them to communicate indirectly. The main code doesn’t need prior knowledge of the implementation details of the callback function, making it easier to replace or modify the behavior without affecting the entire system.

Overall, callback functions enhance the flexibility, modularity, and extensibility of a program, enabling developers to create more dynamic and adaptable software systems.

If you want to learn more about C programming language, then you should check our C tutorials for free.

In our next article, we will discuss the Compilation Steps and Memory Layout of the C Program.

You can also read the below tutorials.

Linux Device Driver TutorialsC Programming Tutorials
FreeRTOS TutorialsNuttX RTOS Tutorials
RTX RTOS TutorialsInterrupts Basics
I2C Protocol – Part 1 (Basics)I2C Protocol – Part 2 (Advanced Topics)
STM32 TutorialsLPC2148 (ARM7) Tutorials
PIC16F877A Tutorials8051 Tutorials
Unit Testing in C TutorialsESP32-IDF Tutorials
Raspberry Pi TutorialsEmbedded Interview Topics
Reset Sequence in ARM Cortex-M4BLE Basics
VIC and NVIC in ARMSPI – Serial Peripheral Interface Protocol
STM32F7 Bootloader TutorialsRaspberry PI Pico Tutorials
STM32F103 Bootloader TutorialsRT-Thread RTOS Tutorials
Zephyr RTOS Tutorials - STM32Zephyr RTOS Tutorials - ESP32
AUTOSAR TutorialsUDS Protocol Tutorials
Product ReviewsSTM32 MikroC Bootloader Tutorial
VHDL Tutorials
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

9 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Table of Contents