Search code examples
crecursionparameter-passinggeneric-programmingcall-by-value

C Code: Passing expression as an argument in recursion call


I am practicing some C questions came across a scenario where a recursive function calls itself with an expression as an argument.

Pow(double x, unsigned n){ 
  .....
  .....
  return Pow(x*x,n/2);
 }

My question is whether the arguments are passed when evaluating the expression (x*x, as in call by value) or does this a lazy evaluation i.e, not evaluated until when used.

Below is the question in detail

Find number of multiplications as result of the call Pow(5.0,12)?

Pow(double x, unsigned n) { 
     if(n==0)   return 1;
     if(n==1)   return x;
     if(n%2==0) return Pow(x*x,n/2);
     else      
     return Pow(x*x,n/2)*x;
}

Options 5,6,8,12


Solution

  • All the arguments of a function in C are evaluated right before the function is called.

    Evaluations and calls in your example:

    Pow(5, 12) = Pow(5 * 5, 6) = 
    Pow(25, 6) = Pow(25 * 25, 3) =
    Pow(625, 3) = Pow(625 * 625, 1) * 625