How exactly does tail recursion work?

前端 未结 8 1588
粉色の甜心
粉色の甜心 2020-12-07 07:39

I almost understand how tail recursion works and the difference between it and a normal recursion. I only don\'t understand why it doesn\'t

8条回答
  •  無奈伤痛
    2020-12-07 07:48

    The compiler is simply able to transform this

    int fac_times (int n, int acc) {
        if (n == 0) return acc;
        else return fac_times(n - 1, acc * n);
    }
    

    into something like this:

    int fac_times (int n, int acc) {
    label:
        if (n == 0) return acc;
        acc *= n--;
        goto label;
    }
    

提交回复
热议问题