《C关键字分析》之typedef与callback

一、typedef定义函数指针类型

1.源码

2.c

#include <stdio.h>
typedef int (*HAL_CALL_BACK)(int,int);

int test(int a,int b);
int add(void* func,int a,int b);

int main(){
//  printf("TK------>>>test is 0x%lx\n",test);
  int result = add((void*) test,3,4);
  printf("TK------>>>>result is %d\n",result);
  return 0;
}

int test(int a,int b){
  return a + b;
}

int add(void* func,int a,int b){
  HAL_CALL_BACK test2 = (HAL_CALL_BACK)func;
  int (*test1)(int,int) = (HAL_CALL_BACK)func;
  //printf("TK------->>>>>func is 0x%lx\n",func);
  return test1(a,b);
}

2.编译运行

gcc -o 2 2.c

./2

TK------>>>>result is 7

二、函数指针类型

1.理解int (* func)(int ,int )

在上面的表达式中从左到右有四个运算符()、*、();

运算符的优先级()比*高,()的结合方向是自左到右,*的结合方向是自右到左;

()结合是从左到右,这是定义了一个指针变量func,接下来是后括号,表明是定义一个函数类型的指针func;

接下来说明该变量func是一个指向,参数是两个int、返回值是一个int的函数,的指针变量。

2.源码

1.c

#include <stdio.h>
//typedef int (*HAL_CALL_BACK)(int,int);

int test(int a,int b);
int add(int func(int,int),int a,int b);

int main(){
//  printf("TK------>>>test is 0x%lx\n",test);
  int result = add(test,3,4);
  printf("TK------>>>>result is %d\n",result);
  return 0;
}

int test(int a,int b){
  return a + b;
}

int add(int func(int,int),int a,int b){
  int (*test1)(int,int) = func;
  //printf("TK------->>>>>func is 0x%lx\n",func);
  return test1(a,b);
}

2.编译和运行

gcc -o 1 1.c

./1

TK------>>>>result is 7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值