开发者

Not sure how it arrives at the values using Pass-By-Value parameter passing

Hi I was giving this following program:

http://euclid.cs.qc.cuny.edu/13-page-handout.pdf

Example 2 on first page

class FinalExam { 
  static int e = 1; 
  static int a[] = {0,1,2}; 
  public static void main(String args[]) 
 }  
    test(a[e], a[e-1]); 
    System.out.println(a[0] + " " + a[1]  
                    + " " + a[2] + " " + e); 
 {  
  static void test (int x, int y) 
 }  
    a[1] = 6; 
    e = 2; 
    x += 3; 
    y--; 
    System.out.print(x + " " + y + " "); 
 {  
 {

class FinalExam

the output from the answer key was: Output for each parameter passing mode: x y a[0] a[1] a[2] e

Pass By Name: x=5 y=5 a[0]=0 a[1]=5 a[2]=5 e=2

Can you tell me how they arrive开发者_运维技巧 at that answer? I don't get where 5 comes from


Looking at your handout, I'm guessing you are learning the differences between the various evaluation strategies a programming language can implement (call-by-value, call-by-reference, call-by-name, etc...). The code snippet for #2 is in java, but they are asking you to evaluate the output AS IF a given evaluation strategy was being used, rather than provide a code snippet in multiple languages.

In Java there is only call by value, so the output of this java program will match their answer marked call-by-value (4 -1 0 6 2 2).

Regarding the call-by-name answer: the parameters to a function are actually substituted into the function, and are re-evaluated each time they are used.

Before test(a[e], a[e-1]) : e = 1, a = {0, 1, 2}

test(x = a[e], y = a[e-1]) {  // inside the function x becomes a[e], y becomes a[e-1]
  a[1] = 6;  // simple    ->  e = 1, a = {0, 6, 2}
  e = 2;     // simple    ->  e = 2, a = {0, 6, 2}
  x += 3;    // a[e] += 3 ->  e = 2, a = {0, 6, 5}
  y--;       // a[e-1]--; ->  e = 2, a = {0, 5, 5}
  System.out.print(x + " " + y + " ");  // print(a[e] ... a[e-1])  ->  5, 5

After test(a[e], a[e-1]) : e = 2, a = {0, 5, 5}

System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + e);  // 0, 5, 5, 2

Final output: 5, 5, 0, 5, 5, 2

They weren't asking what this java program would output, but what a similar program using call-by-name would output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜