2

What is difference between "passed by value-result", "passed by reference" and "passed by name"?

I have a program in C++:

#include <stdio.h>
#include <iostream>
using namespace std;

void swap(int a, int b) {
   int temp;
   temp = a;
   a = b;
   b = temp;
}
int main() {
   int value = 2, list[5] = {1, 3, 5, 7, 9};
   swap(value, list[0]);
   swap(list[0], list[1]);
   swap(value, list[value]);
   return 0;
}

And this is the solution after call swap : https://i.stack.imgur.com/w46SM.jpg I don't know the difference between them. Please help me explain it.

wakjah
  • 4,541
  • 1
  • 18
  • 23
Khuê Phạm
  • 59
  • 1
  • 7
  • 1
    Possible duplicates: [here](http://stackoverflow.com/questions/410593/pass-by-reference-value-in-c), [here](http://stackoverflow.com/questions/2278700/difference-between-call-by-reference-and-call-by-value), and [here](http://stackoverflow.com/questions/2207179/difference-between-value-parameter-and-reference-parameter). – JBentley Dec 19 '13 at 19:52

1 Answers1

1

C++ uses call by value by default, and can use call by reference if the argument is correctly decorated. (Pointer arguments pass the value of the pointer.)

If you specify a reference argument (int& a) in the updated sample below), your swap function will work.

Call by value-result isn't supported by C++; it works by passing the value in at the start of the function and copying the value out at the end of the function.

Call by name is just weird. Instead of passing values, it passes bits of code (aka thunks) that evaluate the variable (in the calling scope). Array references are notorious for not being evaluated as one would expect using call by name.

void swap(int& a, int& b) {
   int temp;
   temp = a;
   a = b;
   b = temp;
}
Eric Brown
  • 13,774
  • 7
  • 30
  • 71