C语言-typedef的用法

1.修饰类型–可以简化代码,类似#define的用法,相当于给类型取了个别名
比如typedef char* A;
则此时A 就相当于char *

{
A a;
}

上述a 就是一个char *类型的指针变量。

2.修饰函数指针–也相当于给函数指针取了别名,指向了函数指针类型,其实就是一个存放函数地址的指针。
typedef int (*PF)(int,int);
PF 就是一个指向形参为两个int类型,返回值为int类型的指针

#include <stdio.h>
typedef int (*PF)(int,int);//函数指针别名
typedef int (*PFS[4])(int, int);//函数指针数组别名
int add(int a, int b) {//两个数相加
	return a + b;
}

int subtract(int a, int b) {//两个数相减
	return a - b;
}
int multiply(int a, int b) {//两个数相乘
	return a * b;
}
int divide(int a, int b) {//两个数相除
	return a / b;//会丢失精度
}
//返回函数指针
PF judge(char buff) {//判断运算符进而选择适合的函数
	switch (buff)
	{
	case '+':return add;
	case '-':return subtract;
	case '*':return multiply;
	case '/':return divide;
	default :return NULL;
		break;
	}
}

int main()
{

	char c = 0;
	int a = 0;
	int b = 0;
	int (*function)(int, int)=NULL;//函数指针
	// PFS b = { NULL };
	int x;
	printf("请输入表达式:\n");
	x=scanf_s("%d%c%d", &a,&c,1,&b);
	function = judge(c);
	if (function != NULL) {	//判断指针是否合法
		printf("表达式%d %c %d = %d\n", a, c, b, function(a, b));
	}else printf("表达式输入错误\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值