Easy Tutorial
❮ Do Not Ignore Web Small Details Android Tutorial End ❯

C Using XOR Operation to Swap Two Numbers

Category Programming Techniques

The XOR operation can achieve the purpose of swapping two numbers, as shown in the code below:

void swap(int &a, int &b)
{
    a = a^b;
    b = a^b;
    a = a^b;
}

However, this method is not recommended, and a comparison with the commonly used temporary variable method is provided below.

Temporary Variable Method:

void swap(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

For the temporary variable method, each assignment only requires reading the value of one variable into the register, and then writing it back to another variable, involving two memory write operations; but for the XOR operation, each operation needs to read two data into the register, perform the operation, and then write the result back to the variable, involving three memory write operations. Additionally, the XOR operation code is less readable.

If you implement both methods in C and compile them with the gcc compiler, you can use the command gcc -S swap.c to view the corresponding assembly code. The temporary variable method results in fewer lines of code, and when using the gcc compiler, swapping arrays with the XOR operation will result in errors, see the link for details.

Without introducing a temporary variable, the values of two numbers can also be swapped using three addition and subtraction operations, as shown below:

void swap(int &a, int &b)
{
    a = a + b;
    b = a - b;
    a = a - b;
}

This method also requires three memory write operations and has poor code readability.

Finally, two comparison images of the assembly code compiled with the three methods (Platform: Ubuntu14.04, gcc 4.8.4) are attached. The swap1.c file corresponds to the temporary variable method, swap2.c corresponds to the addition and subtraction method, and swap3.c corresponds to the XOR method. It can be seen that the assembly code compiled with the temporary variable method is the least in quantity, indicating higher efficiency. The difference between the addition and subtraction method and the XOR method is merely in the calculation method, with the same number of operations.

Figure 1: Comparison of Assembly Code for the Temporary Variable Method and Addition and Subtraction Method, click on the image to view a larger version.

Figure 2: Comparison of Assembly Code for the XOR Method and Addition and Subtraction Method, click on the image to view a larger version.

Original Source: 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

❮ Do Not Ignore Web Small Details Android Tutorial End ❯