XOR operation can achieve the purpose of swapping two numbers, the code is as follows:
void swap(int &a, int &b)
{
a = a^b;
b = a^b;
a = a^b;
}
But this method is not recommended to use,and here is a comparative explanation with the common temporary variable method.
Temporary variable method:
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
For the temporary variable method, each assignment only needs to read the value of one variable into a register, and then write it back from the register to another variable, involving two memory write operations in total. However, for the XOR operation, each time it is necessary to read two data into registers, then perform the operation, and then write the result back to the variable, requiring three memory write operations in total. In addition, the code readability of the XOR operation is poor.
If you use C language to implement the above two methods and compile them with the gcc compiler, you can use the command gcc -S swap.cto view the corresponding assembly code. The temporary variable method has fewer lines of code. In addition, when using thegcccompiler, swapping arrays with XOR operation will cause errors, see the link.
Without introducing a temporary variable, you can also use three addition/subtraction operations to swap the values of two numbers, the code is as follows:
void swap(int &a, int &b)
{
a = a + b;
b = a - b;
a = a - b;
}
This method also requires three memory write operations, and the code readability is also poor.
Finally, attached are two comparison diagrams of the corresponding assembly code after compiling the three methods (platform:Ubuntu14.04,gcc 4.8.4), in the figuresswap1.cthe file corresponds to the temporary variable method,swap2.cthe file corresponds to the addition/subtraction method,swap3.cthe file corresponds to the XOR method. It can be seen that the temporary variable method compiles to the least amount of assembly code, meaning higher efficiency. The difference between the addition/subtraction method and the XOR method is only the calculation method; the operation steps are identical.
Figure 1: Comparison of assembly code between the temporary variable method and the addition/subtraction method. Click the image to view a larger version.
Figure 2: Comparison of assembly code between the XOR method and the addition/subtraction method. Click the image to view a larger version.
Original address: https://tangxuan1023.github.io/2018/02/09/%E4%BA%A4%E6%8D%A2%E4%B8%A4%E6%95%B0%E7%9A%84%E5%80%BC/#more

