Pass-by-value vs Pass-by-reference

Updated: 2021-11-19
  • pass-by-value: passing a copy of the variable to a function.
  • pass-by-reference: passing an alias of the variable to a function.
  • "pass-by-pointer": actually pass-by-value, it is copying the value of the pointer (the address), into the function, and then dereferencing it to get the value.

Languages with both pass-by-value and pass-by-reference

C++:

Declaration Invocation
pass-by-value void f(int x) f(x)
pass-by-reference void f(int& x) f(x)
pass-by-pointer void f(int* x) f(&x)
pass-by-pointer (array) void f(int* arr) f(arr)

Languages with pass-by-value only

Java, Javascript, C, Rust and most other languages do not support any form of pass by reference

In C++ a reference is an alias for another variable. C doesn’t have this concept (so essentially everything in C is pass-by-value).

Similarly Java is always pass-by-value, or "Object references are passed by value".

Pass by Value

The argument’s value is copied into the value of the corresponding function parameter.

void foo(int x) {
  // ...
}

int main() {
  int x = 1;
  foo(x);
}

Pass by Reference

A reference is same object, just with a different name and reference must refer to an object.

void swap(int& x, int& y) {
  int tmp = x;
  x = y;
  y = tmp;
}

int main() {
  int a = 10, 20;
  swap(a, b);
}

Pass by Pointer

void swap(int* x, int* y) {
  int tmp = *x;
  *x = *y;
  *y = tmp;
}

int main() {
  int a = 10, 20;
  swap(&a, &b);
}

Array:

// Definition
double getAverage(int *arr, int size) {}

// call the function
int a[5] = {1000, 2, 3, 17, 50};
avg = getAverage(a, 5);

Refernce vs Pointer

  • References can’t be NULL, they are safer to use.
  • A pointer can be re-assigned while reference cannot, and must be assigned at initialization only.
  • A pointer is a variable that holds a memory address. A reference has the same memory address as the item it references.