0

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

Baldrickk
  • 4,291
  • 1
  • 15
  • 27

3 Answers3

5

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
Curd
  • 12,169
  • 3
  • 35
  • 49
2

A recursive function is a function that performs a call to itself. It's nothing special about the call, it's just a regular function call, just the caller is the same as the callee. So it does passing by value, as it does in every other function call.

Paul92
  • 8,827
  • 1
  • 23
  • 37
0

The correct answer is 4:
The call pow(5,12); does % * / and calls pow(25,6); which does % * / and calls pow(625,3);, which does % * / * and calls pow(390625,1);, which does non.

if you mean all operations like % * or / the answer is 10. if you only mean * and / the answer is 7.

mch
  • 9,424
  • 2
  • 28
  • 42