سؤال

I understand the basic logic of call by copy restore. But I was wondering for a problem like this

void p(int x,int y) {
     x++;
     y+=2;
}

main() {
   int a=10;
   p(a,a);
   // what will be now value of a, 11 or 12?
}
هل كانت مفيدة؟

المحلول

Update: The answer is 12, see update below.

OK, this is actually a good question. So this explains what "copy-restore" is all about: https://stackoverflow.com/a/8871340/171933

Most programming languages don't support copy/restore, but only (some variations) of pass-by-value and pass-by-reference. So it's not so easy to try this out.

However, the question you are interested in is this: Which value wins? Does x get to write its value back to a when the function ends (which would be 11), or does y get to write its value back to a when the function ends (which would be 12).

In a language that supports "copy-restore", I'd hope that this would throw a compiler error.

Update:

After some searching I've found a language that actually supports "copy-restore", namely Ada. This is the code in Ada (this is my first and probably last program written in Ada):

with Ada.Text_IO; use Ada.Text_IO;

procedure copy_restore_example is
        a: integer;

        procedure p(x: in out integer; y: in out integer) is
        begin
                x:= x+1;
                y:= y+2;
        end p;

begin
        a := 10;
        Put_Line("Before :" & natural'image(a));
        p(a, a);
        Put_Line("After :" & natural'image(a));

end copy_restore_example;

The result is 12, y wins. You can run this program in your browser here: http://www.compileonline.com/compile_ada_online.php

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top