pass-by-referencepass-by-valuecall-by-value

What happens when we pass-by-value-result in this function?


Consider this code.

foo(int x, int y){
    x = y + 1;
    y = 10;
    x++;
}
int n = 5;
foo(n,n);
print(n);

if we assume that the language supports pass-by-value result, what would be the answer? As far as I know, pass-by-value-result copies in and out. But I am not sure what would be n's value when it is copied to two different formal parameters. Should x and y act like references? Or should n get the value of either x or y depending on which is copied out last?

Thanks


Solution

  • Regardless of whether it's common pass-by-value or pass-by-value-result, then x and y would become separate copies of n, they are in no way tied to each other, except for the fact they start with the same value.

    However, pass-by-value-result assigns the value back to the original variables upon function exit meaning that n would take on the value of x and y. Which one it gets first (or, more importantly, last, since that will be its final value) is open to interpretation since you haven't specified what language you're actually using.

    The Wikipedia page on this entry has this to say on the subject ("call-by-copy-restore" is its terminology for what you're asking about, and I've emphasised the important bit and paraphrased to make it clearer):

    The semantics of call-by-copy-restore also differ from those of call-by-reference where two or more function arguments alias one another; that is, point to the same variable in the caller's environment.

    Under call-by-reference, writing to one will affect the other immediately; call-by-copy-restore avoids this by giving the function distinct copies, but leaves the result in the caller's environment undefined depending on which of the aliased arguments is copied back first. Will the copies be made in left-to-right order both on entry and on return?

    I would hope that the language specification would clarify actual consistent behaviour so as to avoid all those undefined-behaviour corners you often see in C and C++ :-)

    Examine the code below, slightly modified from your original since I'm inherently lazy and don't want to have to calculate the final values :-)

    foo(int x, int y){
        x = 7;
        y = 42;
    }
    int n = 5;
    foo(n,n);
    print(n);
    

    The immediate possibilities I see as the most likely are: