Is there any hard-wired limit on recursion depth in C

前端 未结 4 1496
野的像风
野的像风 2021-02-13 09:54

The program under discussion attempts to compute sum-of-first-n-natural-numbers using recursion. I know this can be done using a simple formula n

4条回答
  •  难免孤独
    2021-02-13 10:28

    1)Consumption of the stack is expected to be reduced and written as tail recursion optimization.

    gcc -O3 prog.c

    #include 
    
    unsigned long long int add(unsigned long int n, unsigned long long int sum){
        return (n == 0) ? sum : add(n-1, n+sum); //tail recursion form
    }
    
    int main(){
        printf("result : %llu \n", add(1000000, 0));//OK
        return 0;
    }
    

提交回复
热议问题