现在有下面这样一段switch case代码
void start() {printf("System started\n");}
void stop() {printf("System stopped\n");}
void restart() {printf("System restarted\n");}
void shutdown() {printf("System shut down\n");}
switch (command) {
case 1:
start();
break;
case 2:
stop();
break;
case 3:
restart();
break;
case 4:
shutdown();
break;
default:
printf("Unknown command\n");
}
虽然这段代码很直观,但如果命令种类增多,switch-case
语句将变得更加复杂且难以管理。每次增加新命令,都需要修改 switch-case
语句,可能会导致维护上的困难。
现在,我们使用函数指针数组来重构上述代码。通过将每个操作的函数指针存储在数组中,我们可以使用简单的数组索引来调用函数,而不需要编写多个 case
分支。
typedef void (*CommandFunc)();
void start() {printf("System started\n");}
void stop() {printf("System stopped\n");}
void restart() {printf("System restarted\n");}
void shutdown() {printf("System shut down\n");}
// 函数指针数组
CommandFunc commands[] = {
start,
stop,
restart,
shutdown
};
if(command > 0 && (command <= sizeof(commands) / sizeof(CommandFunc)))
commands[command - 1];
else
printf("Unknown command\n");
通过使用函数指针数组,代码的结构更加清晰,添加新功能时只需要增加新的函数并将其指针添加到数组中,无需修改核心逻辑。能让代码更加简洁高效。