很多人的代码里面Switch语句用的比较多,导致代码冗长,可读性很差。而用指针函数代替,可以提升代码的移植性和可读性。而这里分享两种很简单的方法来使你的代码变得更加清晰。
第一种(case表达式的值连续时):
修改前:
#include <stdio.h>
int test_value=0;
int main(void)
{
int i=0;
while(1)
{
switch(i)
{
case 0:
{
test_value=1;
}
break;
case 1:
{
test_value=2;
}
break;
case 2:
{
test_value=3;
}
break;
}
printf("i = %d ,test_value = %d\n",i,test_value);
i++;
if(i==3)
{
break;
}
}
}
输出的结果:
修改后:
#include <stdio.h>
int test_value=0;
void Fun_A(void){test_value=1;}
void Fun_B(void){test_value=2;}
void Fun_C(void){test_value=3;}
void (*pFun[])(void)={
Fun_A,
Fun_B,
Fun_C,
};
int main(void)
{
for(int i=0;i<3;i++)
{
pFun[i]();
printf("修改后:i = %d ,test_value = %d\n",i,test_value);
}
}
输出的结果:
第二种(case表达式值不连续):
修改前:
#include <stdio.h>
int test_value=0;
int main(void)
{
int i=0;
while(1)
{
switch(i)
{
case 1:
{
test_value=1;
}
break;
case 5:
{
test_value=2;
}
break;
case 10:
{
test_value=3;
}
break;
}
printf("i = %d ,test_value = %d\n",i,test_value);
i++;
if(i == 11)
{
break;
}
}
}
输出的结果:
修改后:
#include <stdio.h>
int test_value=0;
void Fun_A(void){test_value=1;}
void Fun_B(void){test_value=2;}
void Fun_C(void){test_value=3;}
typedef struct{
int value;
void (*pFun)(void);
}AKA_FUN;
AKA_FUN test_buff[] = {
{ 0 , Fun_A},
{ 5 , Fun_B},
{ 10 , Fun_C},
};
int main(void)
{
int i=0;
while(1)
{
for(int j=0;j<3;j++)
{
if(test_buff[j].value == i)
{
(test_buff[j].pFun)();
}
}
printf("修改后i = %d ,test_value = %d\n",i,test_value);
i++;
if(i == 11)
{
break;
}
}
}