0
1

More than 1 year has passed since last update.

関数ポインタを使った再帰的呼び出し

Last updated at Posted at 2023-08-27

参考ページ

モノづくり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_
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1