I learned about the callback function in C and found that it is too difficult to understand the concept of a callback.
As I know, a callback function is implemented using a function pointer in c, which means that we can refer to a function using a pointer in the same way as we used a pointer to refer to a variable.
I have two functions:
1. First, the callback function is used.
#include <stdio.h>
int add_two_number(int a, int b);
int call_func(int (*ptr_func)(int, int), int a, int b);
int main (int *argc, char *argv[])
{
printf("%d", call_func(add_two_number, 5, 9));
return 0;
}
int add_two_number(int a, int b)
{
return a + b;
}
int call_func(int (*ptr_func)(int, int), int a, int b)
{
return ptr_func(a, b);
}
2. The second uses a regular function call:
#include <stdio.h>
int add_two_number(int a, int b);
int call_two_number(int a, int b);
int main (int *argc, char *argv[])
{
printf("%d", call_two_number(5, 9));
return 0;
}
int add_two_number(int a, int b)
{
return a + b;
}
int call_two_number(int a, int b)
{
return add_two_number(a, b);
}
These two functions make a simple mathematical addition between the two numbers and the two functions also work correctly, as I expected.
My question is what is the difference between the two? and when do we use callback instead of normal function?