Exchange two variable values, old topic, the following summarizes the various methods are.
For convenience, define two variables first.
int a = 1;int B = 2;
Exchange variable values with a temporary variable of 1
int tmp;tmp = a;//TMP = 1a = b;//A = 2b = tmp;//B = 1
2 Exchange Address
int *p;p = &a;//tmp->1 a = &b;//a->2b = p;//b->1
The second does not use the third variable 1 plus subtraction
A = a + b//a = 3b = a-b//b = 1a = a-b//A = 2
2 Multiplication method
A = A * b//2b =/A//2a = A/b//1
3 XOR Law
a:0000 0001//b:0000 0010a = a ^ b//a:0000 0011b = a ^ b//b:0000 0001a = a ^ b//a:0000 0010
For each of the above methods, the intermediate variable requires additional memory space.
The addition and subtraction and multiplication methods may appear to be out of bounds, or divide by 0, and only apply to numerical operations;
The better one is the last, low-memory operation (/* All kinds of data types */, This place is my mistake, XOR can only be used for integral type, thanks to Xiacanni 's reminders ).
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
The two-digit value that is often used by the interchange algorithm