if_else_switch_case写法

本文介绍了一种使用C语言实现的动态调度方法,通过定义结构体和宏来简化多函数调度过程。文中提供了两种实现方式:一种是利用结构体数组进行函数指针调度;另一种则是采用宏定义结合switch-case语句实现。这两种方法都展示了如何根据不同输入调用相应的处理函数,并输出处理结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一段

#define FUNCTION_COOUNT	3
#define UNDEFINED					-1

typedef struct 
{
	int nFunction_num;
	int (*pFun)(int* nInput,int* nOutput);

}DISPATCH_ITEMS;

DISPATCH_ITEMS sDispatcher[FUNCTION_COOUNT];

int processA(int* pInput,int* pOutput)
{
	*pOutput = 0;
	return 0;
}

int processB(int* pInput,int* pOutput)
{
	*pOutput = 1;
	return 0;
}

int processC(int* pInput,int* pOutput)
{
	*pOutput = 2;
	return 0;
}

int processTotal(int nNum,int* pInput,int* pOutput)
{
	int i = 0;
	for( ; i < FUNCTION_COOUNT ; i++ )
	{
		if(nNum == sDispatcher[i].nFunction_num)
		{
			return (*(sDispatcher[i].pFun))(pInput,pOutput);
		}
	}
	return UNDEFINED;
}

int main(int argc,char** argv)
{
	sDispatcher[0].pFun = processA;
	sDispatcher[0].nFunction_num = 0;
	sDispatcher[1].pFun = processB;
	sDispatcher[1].nFunction_num = 1;
	sDispatcher[2].pFun = processC;
	sDispatcher[2].nFunction_num = 2;
	int nInput = 0;
	int nOutput = 0;
	processTotal(1,&nInput,&nOutput);
	printf("output : %d\n",nOutput);
	system("pause");
	return 0;
}

第二段

#define DISPATCH_BEGIN(x) switch(x) { 
#define DISPATCH_FUNCTION(num, fun) case num : fun(pInput, pOutput) ; break; 
#define DISPATCH_END default : ; }

int processA(int* pInput,int* pOutput)
{
	*pOutput = 0;
	return 0;
}

int processB(int* pInput,int* pOutput)
{
	*pOutput = 1;
	return 0;
}

int processC(int* pInput,int* pOutput)
{
	*pOutput = 2;
	return 0;
}

int process(int nNum,int* pInput,int* pOutput)
{
	DISPATCH_BEGIN(nNum)
	DISPATCH_FUNCTION(0,processA)
	DISPATCH_FUNCTION(1,processB)
	DISPATCH_FUNCTION(2,processC)
	DISPATCH_END
	return 0;
}

int main(int argc,char** argv)
{
	int nF = 2;
	int nI = 0;
	int nO = 0;
	process(nF,&nI,&nO);
	printf("result : %d\n",nO);
	printf("The file is %s.\n", __FILE__);
	printf("The date is %s.\n", __DATE__);
	printf("The time is %s.\n", __TIME__);
	printf("This is line %d.\n", __LINE__);
	printf("This function is %s.\n", __FUNCTION__);
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值