参考ページ
モノづくりC言語塾 C言語 関数ポインタ【ポインタを使って関数を呼ぶ仕組み解説】
準備
今回はオンラインコンパイラを使用します。
オンラインコンパイラ
ソースコード
sample.c
#include <stdio.h>
//関数fを代入することを想定して、関数ポインタuを宣言
int (*u)(int i);
int f(int i){
//引数iを表示
printf("_%d_",i);
//引数iに1を加算
i++;
if(i>10){
//引数iが10より上になったら1を返す
return 1;
}
else{
//関数ポインタuにより、関数fを代理的に再帰呼び出し
u(i);
}
//戻り値として0を返す
return 0;
}
int main() {
//変数iを宣言する
int i;
//0から9まで表示する
for(i=0;i<10;++i){
printf("%d_",i);
}
//変数iに1加算された状態で表示する
printf("_%d",i);
//改行する
printf("¥n");
//関数ポインタuに関数fを代入
u=f;
//関数ポインタuの実行
u(0);
return 0;
}
実行結果
console
0_1_2_3_4_5_6_7_8_9__10¥n_0__1__2__3__4__5__6__7__8__9__10_