Reference Versus Value

What is the difference between reference and value? How can we ‘pass by reference’ versus ‘pass by value’?

#include <iostream> 
 
using namespace std; 
 
// CALL BY VALUE is the default way of passing parameters 
// in C/C++: the parameter is a COPY of the original, so 
// the function can't change the original. 
int changeByValue(int x, int amount); 
 
// CALL BY REFERENCE is indicated by the (&) after the type 
// of the parameter. It means the parameter is initialized 
// as a reference (aka a pointer) to the original value,  
// so it can change the original. 
int changeByRef(int& x, int amount); 
 
int main(){   
    int x = 10; 
    changeByValue(x, 23);   
    cout << "x = " << x; 
    changeByRef(x, 23); 
    cout << "x = " << x; 
    return 0; 
} 
 
int changeByValue(int x, int amount) {
    x = x + amount;   
    return x; 
} 
 
int changeByRef(int& x, int amount) {   
    x = x + amount;   
    return x; 
} 

An illustration by Mathwarehouse:

Gif Reference v Value

Swapping 2 Variables

#include <iostream>
using namespace std;

void swapVals(int& x, int& y){
  int z = x;
  x = y;
  y = z; // original x value
}

int main() {
  int x = 20;
  int y = 5;
  cout << "before swap: x = " << x << " and y = " << y << endl;
  swapVals(x, y);
  cout << " after swap: x = " << x << " and y = " << y << endl;
  return 0;
}

© 2020. Some rights reserved.