state: 0,執行run()
state: 1,執行stop()
state: 2,執行exit()
void run() {
printf("start\r\n");
}
void stop() {
printf("stop\r\n");
}
void exit() {
printf("exit\r\n");
}
bool OnStateChange(uint state) {
if (state == 0) {
run();
}
else if (state == 1) {
stop();
}
else if (state == 2) {
exit();
}
else {
printf("Wrong state!\n");
return false;
}
return true;
}
用if判斷式是最簡單的方法。不過如果state變多。整段code就會變得很冗長。
int OnStateChange(uint state) {
switch (state) {
case 0:
run();
break;
case 1:
stop();
break;
case 2:
exit();
break;
default:
printf("Wrong state!\n");
return false;
}
return 0;
}
改用switch看起來有比較乾淨一點。不過state變多,程式碼也會變得冗長。有沒有什麼更精簡的作法呢?這時候函式指標陣列就派上用場了。
static void (*command[])(void) = {run, stop, exit};
int OnStateChange(uint state) {
if (state > 3) {
printf("Wrong state!\n");
return false;
}
command[state]();
return 0;
}
這種寫法比前兩個例子都來的精簡。函式指標陣列宣告的第一個void表示函式的回傳值,第二個void表示函式的參數。所以這是一個帶有三個函式指標的陣列,陣列中函式的回傳值以及參數都是void。
thx,it helps a lot!!
回覆刪除if (state >= 3) {
回覆刪除printf("Wrong state!\n");
return false;
}
應該要修改成這樣
因為command[3](); 沒有定義.