As we mentioned above, two numbers can be exchanged through an exclusive or operation without any intermediate variables. As shown below:
- Void Exchange (Int & A, Int & B)
- {
- A ^ = B;
- B ^ =;
- A ^ = B;
- }
However, there is a very hidden trap.
When we operate an array, two elements in the array are exchanged, such as exchang (& A [I], & B [J]). if I = J (this is likely to happen), the result is not what we expected.
- Void main ()
- {
- Int A [2] = {1, 2 };
- Exchange (A [0], a [1]); // exchange values of a [0] And a [1]
- Printf ("1 --- A [0] = % d a [1] = % d \ n", a [0], a [1]);
- Exchange (A [0], a [0]); // exchange a [0] with yourself
- Printf ("2 --- A [0] = % d a [1] = % d \ n", a [0], a [1]);
- }
The output of the above test code is:
- 1 --- A [0] = 2 A [1] = 1
- 2 --- A [0] = 0 A [1] = 1
Unexpectedly, the first exchange was executed correctly, but the second exchange call set a [0] to 0. after careful analysis, it is not difficult to find that this is because we use an exception or implement exchange in exchange. If the numbers of input A and B are the same, the code in exchange is equivalent:
- A ^ =;
- A ^ =;
- A ^ =;
The result is of course 0 if a does 3 distinct on its own.
In this case, we cannot adopt an exception or in any place where the exchange is used. Even if it is used, we must determine whether the two numbers are equal before the exchange, as shown below:
- Void Exchange (Int & A, Int & B)
- {
- If (A = B) return; // prevent & A, & B from pointing to the same address; then the result will be incorrect.
- A ^ = B;
- B ^ =;
- A ^ = B;
- }
An exclusive or exchange of two numbers]