C++ Pass by Reference Program
IBM explains C++ pass by reference in the example below (source included).
If I changed void swapnum...
to void swapnum(int i, int j)
, woul开发者_开发问答d 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
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.
Yes, but that means that swapnum will no longer work as the name implies
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.
精彩评论