SoFunction
Updated on 2025-03-10

Callback function examples in C language


#include<>

//The format of the method pointer is: int (*ptr)(char *p) that is: return value (pointer name) (parameter list)
typedef int (*CallBackFun)(char *p);    //Name the callback function, the type is called CallBackFun, and the parameter is char *p

//Method Afun, the format conforms to the format of CallBackFun, so it can be regarded as a CallBackFun
int Afun(char *p)
{
printf("Afun callback prints out the character %s!\n", p);
    return 0;
}

// Method Cfun, the format conforms to the format of CallBackFun, so it can be regarded as a CallBackFun
int Cfun(char *p)
{  
printf("Cfun callback print:%s, Nice to meet you!\n", p);
    return 0;
}

// Execute callback function, method 1: Through naming, pCallBack can be regarded as an alias for CallBackFun
int call(CallBackFun pCallBack, char *p)
{  
printf("call prints out the characters %s!\n", p);
    pCallBack(p);  
    return 0;
}

// Execute the callback function, method 2: Directly pass the method pointer
int call2(char *p, int (*ptr)())  //or int call2(char *p, int (*ptr)(char *)) At the same time, ptr can be named at will
{
    printf("==============\n", p);   
    (*ptr)(p);
}

int main()
{  
    char *p = "hello";
    call(Afun, p);  
    call(Cfun, p);
    call2(p, Afun);  
    call2(p, Cfun);
    return 0;
}
Let's take a look at another callback function example:

#include <>
typedef void (*callback)(char *);
void repeat(callback function, char *para)
{
    function(para);
    function(para);
}

void hello(char* a)
{
     printf("Hello %s\n",(const char *)a);
}

void count(char *num)
{
     int i;
     for(i=1;i<(int)num;i++)
          printf("%d",i);
     putchar('\n');
}

int main(void)
{
     repeat(hello,"Huangyi");
     repeat(count, (char *)4);
}