在 java 或 c++ 中使用 "Call by name" 调用此函数的结果和示例是什么?

What is the result and example of invoking this function using "Call by name" in java or c++?

我刚刚参加了编程语言测验 class 并遇到了这个问题:

假设按名称调用,以下代码的结果是什么:

public class MyClass {

    static int i = 1;

    static float f(int x, int i){
        int s = 0;
        for(i = 0; i <3; i++){
            s = s + x;
        }
        return s;
    }

    static void g(){
        int[] a= {10,30,50};
        int[] b = {20,40,60};
        System.out.println(f(i, i));
        i = 1;
        System.out.println(f(a[i],i));
        i = 1;
       System.out.println(f((a[i] *b[i]), i));
    }  



 public static void main(String[]args){
     g();

 }   
}

上面的代码与我的试卷完全一样,但当时是在纸上,所以我手动计算并得到了结果3.0, 90.0, and 3600.0。 运行自己电脑上的代码后,结果和我计算的一样

但是,问题是多项选择,最接近的选项是 3.0, 90.0, and 4400.0。这让我假设单词 "Call by name" 改变了函数 f 在行 System.out.println(f((a[i] *b[i]), i));

上的调用方式

谁能解释一下 4400.0 在 Java 或 C++ 中是如何实现的?

在按名称调用中,用作参数的表达式直接在被调用函数中替换。 它们不会在调用函数之前求值,而是在函数中参数出现的每个地方被替换

这意味着最后一次调用 f 等同于:

int s = 0;
for(i = 0; i <3; i++){
    s = s + (a[i] * b[i]);
}
return s;

这是最后一次调用 f 的完整步骤序列(我希望这是清楚的):

s = 0
i = 0

s = s + (a[i] * b[i])
  = 0 + (a[0] * b[0])
  = 0 + (10 * 20)
  = 200

i = 1

s = s + (a[i] * b[i])
  = 200 + (a[1] * b[1])
  = 200 + (30 * 40)
  = 200 + 1200
  = 1400

i = 2

s = s + (a[i] * b[i])
  = 1400 + (a[2] * b[2])
  = 1400 + (50 * 60)
  = 1400 + 3000
  = 4400

所以当freturns时,你可以看到s4400