Reputation: 29
I have this snippet of code in C++:
#include <iostream>
using namespace std;
void byRefCPointerByValue (int *x, int *y)
{
int b = 10;
int *aux = x;
x = y;
y = aux;
}
int main ()
{
int a = 1;
int b = 2;
int *x = &a;
int *y = &b;
byRefCPointerByValue(x,y);
cout << *x << endl;
cout << *y << endl;
return 0;
}
I know that, in main function, x and y holds some adresses. When the function is called, the parameters are still addresses, not values. Inside the function, parameteres *x and *y hold actual values, 1 respectively 2. Is it right that the function performs interchange between addresses? Why is that x remains 1 and x remains 2 after calling this function?
Upvotes: 0
Views: 57
Reputation: 122516
The pointers are passed by value, hence the function cannot change the value of the pointers themself. The function could change the value of what x
and y
point to, but it doesnt do that. For comparison, this is how a swap could be implemented:
void simple_swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 1, b = 2;
simple_swap(&a,&b);
}
Note that the fucntion does not modify the pointers, only the values they point to. In your case however,
void byRefCPointerByValue (int *x, int *y)
{
int b = 10;
int *aux = x;
x = y;
y = aux;
}
All modifications to x
and y
are modifications on the local variables x
and y
.
PS I called the function above simple_swap
rather than swap
on purpose. If you write a swap
you should use references and no pointers. However, you shouldn't be writing a swap
for integers in the first place, there is std::swap
for that.
Upvotes: 4
Reputation: 41
When you pass variables to other functions then you create copies of the variables you have passed. In your case, you have created two new pointers x and y in your function which are different from x,y in your main function. You play around with your pointers in the function changing their addresses so you are simply changing the copies of x and y, not x and y of main so there is no change in your values.
You should get more insight on your problem if you change the names of your variables in your function.
Upvotes: 1
Reputation: 11940
Because you swap copies of x
and y
, local to byRefCPointerByValue
. If you wan't to modify the objects at caller's context, pass them by re-ref:
void byRefCPointerByValue (int *&x, int *&y);
(You could simply ask how it's done if that is all you needed to know.)
Upvotes: 2