views:

94

answers:

3

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

+3  A: 

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

Mike
Kevin
@Kevin - That is right you'd pass the address of the pointer.
JonH
If you actually passed *p, *q you'd be passing by value.
JonH
+2  A: 

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.

Stargazer712
+5  A: 

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
You forgot to name your second swapnum method swapByVal
RickNotFred
@RichNotFred - I'd say its still pretty close to Monday so please forgive me :). Edited though.
JonH