# typedef & function pointer ###### tags: `C basics` ### Reference >致謝 Typedef function pointer? https://stackoverflow.com/questions/4295432/typedef-function-pointer/4295495 C 語言 typedef 的用法 >https://magicjackting.pixnet.net/blog/post/65865174 Function pointer in C >https://www.geeksforgeeks.org/function-pointer-in-c/ correct way to assign function pointer https://stackoverflow.com/questions/15280749/correct-way-to-assign-function-pointer typedef is a language construct that associates a name to a type. You use it the same way you would use the original type, for instance ```c= typedef int myinteger; typedef char *mystring; typedef void (*myfunc)(); myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; myfunc f; // compile equally as void (*f)(); ``` ```c= // Examples of typedef a function or pointer of function typedef int IamFunc (int, int); // (1) typedef int * IamFunc (int, int); // (2) typedef int (*IamFunc)(int, int); // (3) ``` (1) 定義一個別名IamFunc,傳回值為整數且需要二個整數參數的函數 (2) 只是回傳值由int變為int*,因為IamFunc右邊的運算子(), 比在左邊的取值運算子*,優先權較高 (3) 多加了括號,因此*,會先執行,所以函數變成指向函數的指標 ![](https://i.imgur.com/lXCSyfC.png) 可以簡單分成紅藍黃三個區塊 紅色:function return value 藍色:name to be defined. 有*代表是指到這個函數型態的指標 黃色:function arguments 下面三種寫法都是等價的: ```c= void printA(char *str) { printf("in A: %s\n", str); return; } int main(int argc, char **argv) { // METHOD 1 void (*func_ptr1)(char*) = &printA; func_ptr1("How about you?"); // METHOD 2 myfunc_t* func_ptr2 = &printA; func_ptr2("How are you?"); // METHOD 3 myfuncptr_t func_ptr3 = &printA; func_ptr3("How old are you?"); return EXIT_SUCCESS; } ``` ![](https://i.imgur.com/YnxBXkn.png) method 1有點難看,使用typedef會好看很多 :> assign to function pointer也可以寫成 ```c= myfunc_t* func_ptr2 = &printA; myfunc_t* func_ptr2 = printA; ``` 呼叫的方式也可以寫成 ```c= func_ptr2("How are you?"); (*func_ptr2)("How are you?"); ```