# 重拾 C 語言::函式指標 ## 進入正題 ```c= void (*foo)(); ``` ```c= int (*ftpr1)(int); int n = 5; int square(int num){ return num*num; } ftpr1 = square; printf("%d",ftpr1(n)) ``` 其中 `ftpr1 = square;` 其實被精簡過了。原本應該長這樣: ```c= ftpr1 = □ ``` ### 傳入函式指標 ```c= int add(int num1, int num2){ return num1 + num2; } int sub(int num1, int num2){ return num1 - num2; } typedef int (*ftprOperation)(int, int); int compute(ftrOperation operation, int num1, int num2){ return operation(num1, num2); } compute(add, 2, 3); compute(sub, 2, 3); ``` ### 傳回函式指標 既然能夠傳入函式指標,我們同樣也可以利用函式回傳函式指標增加程式的彈性。 ```c= fptrOperation select(char opcode){ switch(opcode){ case '+': return add; case '-': return sub; } } fptrOperation select(char opcode, int num1, int num2){ fptrOperation operation = select(opcode); return operation(num1, num2); } printf("%d\n", evaluate('+', 5, 6)); printf("%d\n", evaluate('-', 5, 6)); ``` ### 使用函數指標的陣列 ```c= typedef int (*operation)(int, int); operation operations[128] = {NULL}; ``` 若不使用 `typedef` ,可以使用: ```c= int (*operations[128])(int, int) = {NULL}; ``` ASCII 的範圍剛好是從 0 - 127 ,一共128個,我們可以加以利用: ![ASCII](https://i.stack.imgur.com/bwCFl.gif) 我們對先前的範例稍加修改: ```c= typedef int (*operation)(int, int); operation operations[128] = {NULL}; int add(int num1, int num2){ return num1 + num2; } int sub(int num1, int num2){ return num1 - num2; } void initOpArray(char opcode){ switch(opcode){ case '+': operations['+'] = add; case '-': operations['-'] = sub; } } int evaluateArray(char opcode, int num1, int num2){ operation doSomething; doSomething = oprations[opcode]; return doSomething(num1, num2); } ``` > declare a as array of pointer to function returning pointer to function returning pointer to char ```c= char *(*(*a[])())() ```