Pass-by-name and Pass-by-value-result

3k views Asked by At

For my programming languages class, I am trying to understand how pass-by-name and pass-by-value-result work. I realize these aren't used hardly at all in mainstream languages, but I am wanting to get a feel for how they work. As an example (language agnostic):

void swap(int a, int b){
    int t;
    t = a;
    a = b;
    b = t;
}
void main() {
    int val = 1, list[5] = {1, 2, 3, 4, 5}
    swap(val, list[val]); 
}

What would the values of val and list be after swap is called for both pass-by-value-result and pass-by-name.

An explanation would be great too.

From what I deduced, it got value-result: val=2, list={1,1,3,4,5} and name: val=3, list={1,2,1,4,5}. I'm very unsure about those results.

Also does it change the way both of these methods work when an array is passed as opposed to a single int? Thanks for any help in advance.

2

There are 2 answers

0
rgafonso On

If you mean pass by name as pass by reference then the result will be the same as by value.
This is because you are only switching references between val and list position val. You are not passing an array reference. Think of a var as a pointer to a block of memory that contains a value.

0
ma1169 On

this code explain one of the problem of pass by name this is why

in swap this is what happen

void swap(int a, int b){
    int t;
    t = a; //t=val; t=1
    a = b;// val=list[val]; val=list[1]=2
    b = t;// list[val]=t; list[2]=1
}
void main() {
    int val = 1, list[5] = {1, 2, 3, 4, 5}
    swap(val, list[val]); 
}

as you can see the val changed at val=list[val] and it isn't the same val you passed anymore

as for pass by value result

void swap(int a=1, int b=2){
    int t;
    t = a; //a=1 so t=1
    a = b; //b=2 so a=2
    b = t; //b=1 so it and it return the right parameter so list[1]=2
}

i hope this helped