總網頁瀏覽量

2019年2月26日 星期二

【C語言觀念複習筆記】函式指標陣列(Array of function pointer)



之前寫過一篇文章討論過指標陣列的觀念

這個指標陣列的指標當然也是有型態的, 上述文章是char

而也可以是指向function

因為指標陣列在上面文章討論過了, 所以先簡單補充一下函數指標的最基礎觀念 透過下列簡單範例說明:

簡單的範例如下:
#include "stdio.h"

void (*foo)();

void show(void)
{

 puts("OMG\n");

}


int main()
{
 int a;
 foo = show;
 foo();
 
 return 0;
}

執行結果會看到 OMG字串顯示


而函數指標陣列就是結合上面(指標陣列 & 函數指標的觀念)



這邊舉個範例,簡單來說是要將下面這段C code的if-else條件改成以函式指標陣列(array of function pointer)的方式改寫

#include "stdio.h"

#include "stdlib.h"

int plus(int a, int b) { return a + b; }
int minus(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divided(int a, int b) { return a / b; }
int main()
{
 int a, c;
 char b;
 printf("key a Function \nEX: 1 + 1\n");
 scanf("%i %c %i", &a, &b, &c);

 if (b == '+')
  printf("%d %c %d = %d\n", a, b, c, plus(a, c));
 else if (b == '-')
  printf("%d %c %d = %d\n", a, b, c, minus(a, c));
 else if (b == '*')
  printf("%d %c %d = %d\n", a, b, c, multiply(a, c));
 else if (b == '/')
  printf("%d %c %d = %d\n", a, b, c, divided(a, c));
}



原程式碼的寫法的問題在於如果條件越多時,那if-else條件式勢必隨條件加長,易使得程式變得攏長,可透過函式指標陣列的方式改善此問題。
改寫如下
#include"stdio.h"

int plus(int a, int b){ return a+b; }
int minus(int a, int b){ return a-b; }
int multiply(int a, int b){ return a*b; }
int divided(int a, int b){ return a/b; }

int main(){
    int a, c;
    char b;
    scanf("%d %c %d", &a, &b, &c);
    
    int (*cmd[])(int a, int c) = {multiply, plus, NULL, minus, NULL, divided};

    printf("%d\n",cmd[b-42](a,c));  // '*' ASCII = 42(0x2a)  ,'+' ASCII = 43 (0x2b), '-' ASCII = 45, '/' ASCII = 47    

    return 0;
}

按照上述寫法加以測試,例如輸入 6*5 就會看到印出的結果30,執行結果畫面如下:




【若需要嵌入式系統技術輔導課程 可來信洽談合作方式: iws6645@gmail.com,亦可先點擊參考這篇介紹文章



沒有留言:

張貼留言