S
storyGerald
I knew some ways of swapping two ints without using a temporary
variable. Just like:
// Method 1:
void swap1(int &a, int &b) {
int temp = a;
a = b;
b = a;
}
// Method 2:
void swap2(int &a, int &b) {
a = a + b;
b = a - b;
a = a - b;
}
// Method 3:
void swap(int &a, int &b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
But I don't know the difference among these ways. The third method is
read from a book, and the author said that would be some cases where
this method can't be used. I don't why, Would you please help me solve
this puzzle?
Thank you!
Gerald
variable. Just like:
// Method 1:
void swap1(int &a, int &b) {
int temp = a;
a = b;
b = a;
}
// Method 2:
void swap2(int &a, int &b) {
a = a + b;
b = a - b;
a = a - b;
}
// Method 3:
void swap(int &a, int &b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
But I don't know the difference among these ways. The third method is
read from a book, and the author said that would be some cases where
this method can't be used. I don't why, Would you please help me solve
this puzzle?
Thank you!
Gerald