0

IBM explains C++ pass by reference in the example below (source included).

If I changed void swapnum... to void swapnum(int i, int j), would it become pass by value?

// pass by reference example
// author - ibm

#include <stdio.h>

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(a, b);
  printf("A is %d and B is %d\n", a, b);
  return 0;
}

Source

In silico
  • 51,091
  • 10
  • 150
  • 143
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384

3 Answers3

6

Any swapping performed if you pass by value are only affected or seen within the function they are passed into and not the calling code. In addition, once you return back to main you will see that a and b did not swap. That is why when swapping numbers you want to pass by ref.

If you are just asking if that is what it would be called, then yes you are right, you would be passing by value.

Here is an example:

#include <stdio.h>

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

void swapByVal(int i, int j) {
  int temp = i;
  i = j;
  j = temp;
}

int main(void) {
  int a = 10;
  int b = 20;

  swapnum(a, b);
  printf("swapnum A is %d and B is %d\n", a, b);

  swapByVal(a, b);
  printf("swapByVal A is %d and B is %d\n", a, b);

  return 0;
}

Run this code and you should see that changes persist only by swapping by reference, that is after we've returned back to main the values are swapped. If you pass by value, you will see that calling this function and returning back to main that in fact a and b did not swap.

JonH
  • 32,732
  • 12
  • 87
  • 145
  • You forgot to name your second swapnum method swapByVal – RickNotFred Aug 03 '10 at 18:04
  • @RichNotFred - I'd say its still pretty close to Monday so please forgive me :). Edited though. – JonH Aug 03 '10 at 18:05
  • Actually, it would be better to understand what happens if we run swapByVal first in this code. Since we run pass by ref first, the values of x and y are already changed. Running pass by value argument first would help for understanding. Great code, thanks. – Michael C. May 24 '18 at 08:54
3

Yes, but that means that swapnum will no longer work as the name implies

Mike
  • 3,462
  • 22
  • 25
2

Yes. The '&' operator specifies that the parameter should point to the memory address of what was passed in.

By removing this operator, a copy of the object is made and passed to the function.

riwalk
  • 14,033
  • 6
  • 51
  • 68