こんばんは。きわさです。
今回はC言語の関数ポインタについてです。
呼び出す関数を動的に決定したいときなどに便利です。
まずは普通の関数呼び出しから。
void main(void) {
int c;
c = testFunc(1, 2);
return;
}
int testFunc(int a, int b) {
return a + b;
}
main関数の他に testFunc があります。testFunc は、引数aとbを足した結果を返却する関数です。
c = testFunc(1, 2)では、1と2をtestFuncに渡して処理を行った結果がcに代入されます。
関数ポインタを使ってみます。
typedef int (*testFunc_t)(int a, int b);
void main(void) {
int c;
testFunc_t func;
func = &testFunc;
if(func) {
c = (func)(1, 2);
}
return;
}
int testFunc(int a, int b) {
return a + b;
}
まずはtypedefです。
testFuncと同じように、引数にint型aとbを受け取りint型を返却する関数のポインタとして testFunc_t型を定義しています。
main関数では、testFunc_t型のfuncにtestFuncのポインタを代入しています。
そして、c = (func)(1, 2)では、funcのポインタが示す関数(testFunc)に引数1と2を渡して実行しています。
funcはポインタ型なので、実行前にif(func)のようにNULLの考慮があったほうが安全です。
