I'm cofused by the pass-by-reference section

void swap_num(int &i, int &j) {

  int temp = i;
  i = j;
  j = temp;

}

int main() {

  int a = 100;
  int b = 200;

  swap_num(a, b);

  std::cout << "A is " << a << "\n";
  std::cout << "B is " << b << "\n";

}

According to code academy, the code as such will swap the numbers in the results so that A is B and B is A. However, if you remove the & (making it a reference no longer) it will just print A is A and B is B.

I completed the exercise but I don’t feel that it very well explained how making something a reference changes it’s value or changes how the code is out-put.

Hello! When you pass something by reference, a change to the parameter will directly affect the value of the variable passed into the function. Say if we took a function:

void add_num(int &no1, int no2) {
no1 = no1 + no2;
no2 = 5;
}

When we run the code:

int main() {

  int a = 100;
  int b = 200;

  add_num(a, b);

  std::cout << "A is " << a << "\n";
  std::cout << "B is " << b << "\n";

}

Since we passed no1 by reference, the variable a is directly changed, so the value of a after running the function is now 300. Since no2 was not passed by reference, it does not get altered in the function.

Passed by reference and not essentially have something to do with memory: when you pass something by reference, they refer to the same place in memory, whereas when you don’t pass something by reference, a copy of that object is made, so the original isn’t altered.
Here is some more reading on it.
I hope this helps!

2 Likes

That does help, thanks, it’s a better explanation than the lesson, even though this is still kind of a weird one for me to wrap my head around…

1 Like