2015年7月9日 星期四

[C筆記]函式指標陣列配合enum當陣列索引值

前言:函式本身就是指標,這裡利用宣告指標陣列來將函式放進陣列裡,利用迴圈將函式通通跑一遍(優點是程式碼看起來精簡,容易擴充其他函式)。

通常會先去判斷enum item
if(enum item ==??)

{  

 再決定要帶入哪一個函式   但是這樣寫未免太複雜

}

...

...

...

...

if(enum item ==??)

{   

每新增一個函式   就外加一段 if 寫下來造成程式的冗長,容易混亂!!

}

這裡利用下列方法改良! 

enum item{AFUNCTION,BFUNCTION,CFUNCTION,DFUNCTION,NEWFUNCTION};  

enum可當索引值AFUNCTION=0,BFUNCTION=1,CFUNCTION=2,DFUNCTION=3

response r[] ={{"chou", AFUNCTION},{"yi", BFUNCTION},{"ming", CFUNCTION},{"pig",DFUNCTION},{"new", NEWFUNCTION}}; 

function[r[i].type](r[i]);  //這行不變


smaple code:

#include <stdio.h>
#include <stdlib.h>
 enum item{AFUNCTION,BFUNCTION,CFUNCTION,DFUNCTION};
//enum 設定 symbol AFUNCTION=0,BFUNCTION=1,CFUNCTION=2,DFUNCTION=3
 typedef struct{
         char *name;
         enum item type;
         }response;
void afunction(response r)
 {
      printf("%s\n",r.name);
      }
       
 void bfunction(response r)
 {
      printf("%s\n",r.name);
      }
       
 void cfunction(response r)
 {
      printf("%s\n",r.name);
      }
       
 void dfunction(response r)
 {
      printf("%s\n",r.name);
      }
int main(int argc, char *argv[])
{
  response r[] ={{"chou",AFUNCTION},{"yi",BFUNCTION},{"ming",CFUNCTION},{"pig",DFUNCTION}};
  
  void (*function[])(response) ={afunction,bfunction,cfunction,dfunction};
//將函釋放入 函式指標陣列裡!
  int i;
  for(i=0;i<4;i++)
  {
   function[r[i].type](r[i]);  
                  } 
  system("PAUSE");
  return 0;
}

執行結果:

沒有留言:

張貼留言