C language learning in-depth review: function pointers and callback functions

Function pointer and a callback function

Function pointer variable is a pointer to function. Function pointer can be as general as a function for calling the function, passing parameters.

Function pointer declared

returnType (*functionPointerName)(param1Type,param2Type...); // 声明一个指向同样参数、返回值的函数指针类型

Examples are as follows:

#include <stdio.h>
 
int max(int x, int y)
{
    return x > y ? x : y;
}
 
int main(void)
{
    /*p 是函数指针 */
    int (*p)(int, int);
    p = &max; // &可以省略
    int a=15, b=10, c=20, d;
    /* 与直接调用函数等价,d = max(max(a, b), c) */
    d = p(p(a, b), c); 
    printf("最大的数字是: %d\n", d);
    return 0;
}

Callback

, The callback function is a function call through a function pointer function pointer variables can be used as a parameter to a function.

As an example:

#include <stdlib.h>  
#include <stdio.h>
/*
populate 填充
*/
// 接受回调函数的函数
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{   //在32位系统中size_t是4字节的,而在64位系统中,size_t是8字节的
    for (size_t i=0; i<arraySize; i++)
        //函数指针调用
        {array[i] = getNextValue();}
}
 
// 获取随机值的回调函数
int getNextRandomValue(void){return rand();}
 
int main(void)
{
    int myarray[10];
    populate_array(myarray, 10, getNextRandomValue);
    for(int i = 0; i < 10; i++) {
        printf("%d ", myarray[i]);
    }
    printf("\n");
    return 0;
}

 

Published 161 original articles · won praise 90 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_42415326/article/details/104027371