Call-by-Value

C++ ordinarily uses call-by-value parameters in functions. C++ programs always allocate a chunk of memory for each call-by-value parameter and C++ programs always arrange for argument values to be copied into that chunk of memory. The rationale is that you want to isolate each function's parameters from other parameters, local variables, and global variables that happen to have the same name.

Example of Call-by-Value

#include <iostream.h>

void f(int a){
  a = a + 5;
  cout << a << endl;
}
int main(){
  int x = 10;
  f(x);
  cout << x << endl;
  return 0;
}

Results:
15
10

Call-by-Reference

One important reason to use call-by-reference parameters is that you may wish to write a function that modifies one of its arguments, which it cannot do if it has only a copy with which to work.

Example of Call-By-Reference


#include <iostream.h>

void f(int& a){
  a = a + 5;
  cout << a << endl;
}
int main (){
  int x = 10;
  f(x);  
  cout << x << endl;
  return 0;
}

Results:
15
15