C++ Pass by Reference Program

前端 未结 3 1166
不思量自难忘°
不思量自难忘° 2020-12-20 09:30

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

If I changed void swapnum... to void swapnum(int i, int j), wou

相关标签:
3条回答
  • 2020-12-20 09:58

    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.

    0 讨论(0)
  • 2020-12-20 10:12

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

    0 讨论(0)
  • 2020-12-20 10:16

    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.

    0 讨论(0)
提交回复
热议问题