Callback Function in C Programming

If you learning or working on any programming language, someone has 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 the 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 mechanism.

What is the callback function in C with example?

What is a callback?

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 callback when he finish his work. The barber agreed. Now, Mr.John can do some other work that he wanted 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. But what is a callback in the C programming language?

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 in understanding the callback functions.

  • 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 Functions

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

Example Code

The following code will help you to understand the callback mechanism. 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 are passing the function pointer to the function test_loop. When the value is equal to 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 do we need a function pointer here. Instead, we can directly call the 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.

#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

What are the advantages of the callback functions?

  • The main advantage of using callbacks is that you can call a function that is defined in a higher software level from a lower software level subroutine.
  • A callback can be used for notifications or signals.

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
VHDL TutorialsUDS Protocol Tutorials
Product Reviews
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