Skip to content

Callbacks function in C

The callback is simply any executable code that is passed as an argument to other code. A function that would receive a function pointer as an argument can call back the function.
Callbacks may also be used to control whether a function acts or not. For example HAL_UART_RxCpltCallback function that we used before  in the
STM32 Nextion Screen Led Toggle blog post. This function runs every Rx Transfer on UART receive completed. An example is an easy way to understand Callback in C.

Let’s look at the example below.

#include<stdio.h>

void my_event() {

   printf(“This is a normal function.”);

}

void callback_event(void (*ptr)()) {

   printf(“This is callback function.\n”);

   (*ptr)();   //calling the callback function

}

void main() {

   void (*ptr)() = &my_event;

   callback_event(ptr);

}

 

 Output:

In that example, we can write only

 callback_event(my_event);

Because the name of the function returns a pointer.

}

Published inC programming 101

Be First to Comment

Leave a Reply

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