C代码:在递归调用中将表达式作为参数传递

Pha*_*mmi 0 c recursion parameter-passing generic-programming call-by-value

我正在练习一些C问题遇到一个递归函数用表达式作为参数调用自身的场景.

Pow(double x, unsigned n){ 
  .....
  .....
  return Pow(x*x,n/2);
 }
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否计算表达式(X*X,如在由值调用)时,参数被传递或执行此一惰性求即,不评价使用时为止.

以下是详细问题

查找调用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;
}
Run Code Online (Sandbox Code Playgroud)

选项5,6,8,12

Cur*_*urd 5

在调用函数之前,将对C中函数的所有参数进行求值.

您的示例中的评估和调用:

Pow(5, 12) = Pow(5 * 5, 6) = 
Pow(25, 6) = Pow(25 * 25, 3) =
Pow(625, 3) = Pow(625 * 625, 1) * 625
Run Code Online (Sandbox Code Playgroud)