文章目录
- 回调函数实现例子
- 四则运算的简单回调函数例子
- 状态机实现例子
函数返回值类型 (* 指针变量名) (函数参数列表);
回调函数实现例子
int Callback_1(int a)
{
printf("Hello, this is Callback_1: a = %d ", a);
return 0;
}
int Callback_2(int b)
{
printf("Hello, this is Callback_2: b = %d ", b);
return 0;
}
int Callback_3(int c)
{
printf("Hello, this is Callback_3: c = %d ", c);
return 0;
}
int Handle(int x, int (*Callback)(int))
{
Callback(x);
}
int main()
{
Handle(4, Callback_1);
Handle(5, Callback_2);
Handle(6, Callback_3);
return 0;
}
四则运算的简单回调函数例子
#include <stdio.h>
#include <stdlib.h>
typedef struct _OP
{
float (*p_add)(float, float);
float (*p_sub)(float, float);
float (*p_mul)(float, float);
float (*p_div)(float, float);
} OP;
float ADD(float a, float b)
{
return a + b;
}
float SUB(float a, float b)
{
return a - b;
}
float MUL(float a, float b)
{
return a * b;
}
float DIV(float a, float b)
{
return a / b;
}
void init_op(OP *op)
{
op->p_add = ADD;
op->p_sub = SUB;
op->p_mul = &MUL;
op->p_div = &DIV;
}
float add_sub_mul_div(float a, float b, float (*op_func)(float, float))
{
return (*op_func)(a, b);
}
int main(int argc, char *argv[])
{
OP *op = (OP *)malloc(sizeof(OP));
init_op(op);
printf("ADD = %f, SUB = %f, MUL = %f, DIV = %f\n", (op->p_add)(1.3, 2.2), (*op->p_sub)(1.3, 2.2),
(op->p_mul)(1.3, 2.2), (*op->p_div)(1.3, 2.2));
printf("ADD = %f, SUB = %f, MUL = %f, DIV = %f\n",
add_sub_mul_div(1.3, 2.2, ADD),
add_sub_mul_div(1.3, 2.2, SUB),
add_sub_mul_div(1.3, 2.2, MUL),
add_sub_mul_div(1.3, 2.2, DIV));
return 0;
}
状态机实现例子
extern void power_off(void);
extern void power_on(void);
extern void low_power_mod(void);
extern void wait_mod(void);
typedef enum
{
WORK_ON_CLOSE = 0,
WORK_ON_OPEN,
WORK_ON_SLEEP,
WORK_ON_WAIT,
} work_status_list_e;
typedef struct
{
uint8_t status;
uint8_t (*function)(void);
} work_status_t;
work_status_t work_status_tabs[] =
{
{WORK_ON_CLOSE, power_off},
{WORK_ON_OPEN, power_on},
{WORK_ON_SLEEP, low_power_mode},
{WORK_ON_WAIT, wait_mode},
};
uint8_t work_status_call(uint8_t status)
{
uint8_t i = 0;
for(i = 0; i < 12; i++)
{
if(status == work_status_tabs[i].status)
{
return work_status_tabs[i].function();
}
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)