An exclusive or exchange of two numbers]

Source: Internet
Author: User

As we mentioned above, two numbers can be exchanged through an exclusive or operation without any intermediate variables. As shown below:

  1. Void Exchange (Int & A, Int & B)
  2. {
  3. A ^ = B;
  4. B ^ =;
  5. A ^ = B;
  6. }


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.

  1. Void main ()
  2. {
  3. Int A [2] = {1, 2 };
  4. Exchange (A [0], a [1]); // exchange values of a [0] And a [1]
  5. Printf ("1 --- A [0] = % d a [1] = % d \ n", a [0], a [1]);
  6. Exchange (A [0], a [0]); // exchange a [0] with yourself
  7. Printf ("2 --- A [0] = % d a [1] = % d \ n", a [0], a [1]);
  8. }

The output of the above test code is:

  1. 1 --- A [0] = 2 A [1] = 1
  2. 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:

  1. A ^ =;
  2. A ^ =;
  3. 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:

    1. Void Exchange (Int & A, Int & B)
    2. {
    3. If (A = B) return; // prevent & A, & B from pointing to the same address; then the result will be incorrect.
    4. A ^ = B;
    5. B ^ =;
    6. A ^ = B;
    7. }

An exclusive or exchange of two numbers]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.