Swap Function (Why does "*a = *b" work?)

Hi. I've been working through tutorials and while playing with Swapping functions, I found that a single statement '*a = *b' successfully swaps two integers. I Googled a bit and couldn't find out why this works. Can someone explain?

How can the following function actually swap the values? Given x = 1 and y = 2, I expected the following code to only change x to 2, but, instead, x becomes 2 and y becomes 1...a successful swap occurs.

1
2
3
4
5
6
7
8
9
10
void swap (int *a, int *b){
	*a = *b;
}

int main(){
	int x = 1;
	int y = 2;
	swap(x,y);
	cout << "x=" << x << ", y=" << y << "\n";
}


Thanks for shedding some light on this...I'm just curious.
I found that a single statement '*a = *b' successfully swaps two integers.

No, you didn't.

You are including a standard header that brings in std::swap which is what is being called in your code since you also have a using namespace std; directive in your code.


Try changing the name:

1
2
3
4
5
6
7
8
9
void myswap(int*a, int* b) {
    *a = *b;
}

int main() {
    int x=1, y=2;
    myswap(x,y);
    cout << "x=" << x << ", y=" << y << '\n' ;
}


And you'll notice that your code doesn't even compile.

http://ideone.com/bO9XAV
http://ideone.com/10Yl4j
Last edited on
Thanks a bunch, cire!!
Topic archived. No new replies allowed.