0

I'm self teaching myself some parameter passing implementation models and in my programming languages book it asks me to write a program to produce different behavior depending on whether pass by reference or pass by value result is used in its parameter passing. What are some leading questions that would help me understand and get to this answer?

I know pass by reference passes the location of the variable and is modified directly by the function while pass by value result copies the value in then copies it back out. I just can't think of a situation where the result would be different (maybe I'm misunderstanding pass by value result?).

Michael Kimin Choo
  • 165
  • 1
  • 4
  • 10
  • 1
    Yes, you're misunderstanding pass by value. Pass by value passes a _copy_ of the parameter. Changes made to it in the called function are _not_ copied back to the caller. (Well, at least in every language I know of. You didn't specify language.) – Carey Gregory Mar 11 '14 at 03:42
  • It's pass by value result not pass by value. – Michael Kimin Choo Mar 11 '14 at 03:44
  • 1
    Hint: What if the object being passed around has side effects when it's constructed/destructed? – cactus1 Mar 11 '14 at 03:44
  • 1
    Sorry, I did not read your question correctly, but it looks like it's probably a duplicate. See http://stackoverflow.com/questions/5768721/pass-by-value-result – Carey Gregory Mar 11 '14 at 03:48
  • Thanks for the help, the link really helped me out. I think I didn't find any results because I was searching for pass by value reference instead of pass by value result :| – Michael Kimin Choo Mar 11 '14 at 04:15

1 Answers1

1
// Correct implementation of a function addToMyself() as the name suggests
void addToMyself(int &a, int b) {
    a += b;
}

// Incorrect implementation
void addToMyself(int a, int b) {
    a += b;
}

// Tweaked implentation with pass by value
int addTwo(int a, int b) {
    return a+b;
}
// and use 
a = addTwo(a, b)
Sid
  • 29
  • 4