Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

天才
Lv 5
天才 asked in 電腦與網際網路程式設計 · 2 decades ago

call by reference與call by name

int a = 1, b = 4;void func1(x, y, z) { y = y + 3; z = x + x;   print x,y,z;}int main() { func1(a+b, a, a);}call-by-valuecall-by-addresscall-by-name 分別會輸出什麼結果?

Update:

再問一下:

int main(){

func1(b+a, a+b, a);

}

void func1(x, y, z){}

這樣子的話x指向b,y指向a,z指向a對嗎?

3 Answers

Rating
  • 2 decades ago
    Favorite Answer

    call-by-value 5,4,10

    y=y+3;.................//y=4;

    z=x+x;................//z=10;

    call-by-address 5,10,10

    y=y+3;................//y=4 & z=4 ∵都指向a位址

    z=x+x;................//z=10 & y=10 ∵都指向a位址

    call-by-name 20,16,16

    func1(a+b, a, a);

    a=a+3;.................//a=4 & a+b=8;

    a=(a+b)+(a+b);..............//a=16

    print x,y,z;==>print a+b,a,a;==>print 16+4,16,16==>print 20,16,16

  • ?
    Lv 5
    2 decades ago

    問的人並沒說是用C. 他主要是想知道不同參數的傳遞方法.

    請參考程式語言的書. 書中會說有幾種參數傳遞方法.

  • 2 decades ago

    int a = 1, b = 4;

    void func1(x, y, z) {

     y = y + 3;

     z = x + x;

    print x,y,z;

    }

    int main() {

     func1(a+b, a, a);

    }

    在C中如果沒有用指標來做的話, 充其量就只會用到Call by Value....所以你呼叫func1()的參數, a+b因為是個運算式所以會用call by value, 但因 a 和 b 被定義為全域變數, 所以 全域變數 a 會被bind 到func1的 y and z, 即 a 和 y 和 z 是彼此互為別名, 實則指向同一塊記憶體, 所以print x,y,z 會印出 1+4, 10, 10......

    以上應是你的程所會跑出的成果....

    ps.另外, 給您個建議, 可以少用全域變數就少用, 因為程式會變得不好DEBUG和維護, (雖然它用起來很方便)

Still have questions? Get your answers by asking now.