Search code examples
cfunctionrecursionreturn

How recursion return the value?


1. #include<stdio.h> 

    int recursion_check(int i);

 
    main(){

         printf("%d",recursion_check(6));
    }
    
    int recursion_check(int i){
    
    if(i==0)
    return 5;
    
    else{
        recursion_check(i-1);
        }
        
    }

I am calling a function (recursion check) form main function and getting return value but there is no return in else case how i am getting return value?


Solution

  • Welcome to undefined behavior.

    The reason why it works on your (supposedly) common computer is because register-sized or smaller integer returns on Intel platforms are done by writing to the RAX/EAX/AX register, and so most compilers on these platforms will avoid using that register for calculations if they can avoid it.

    And so when your function eventually gets to a valid return and writes to the RAX register, and then returns out of the entire call chain, the function that initially called your recursive function will read RAX and it'll get the 5 that was written once.

    Of course, nothing stops the compiler from not doing this at all. It doesn't have to use RAX, and it doesn't have to avoid using it for other computations. Hence, undefined behaviour.