Function for exchanging two numbers: int swap (Int & A, Int & B)

Source: Internet
Author: User

Recently, I suddenly forgot the constraints for the clever writing of two integers, so I read it again:

# Include <iostream> using namespace STD; int A [] = {1, 2, 4}; void swap (Int & A, Int & B) {A = a ^ B; B = a ^ B; A = a ^ B;} int main () {int M = 1, n = 2; swap (m, n ); swap (A [1], a [1]); cout <m <"" <n <Endl; For (INT I = 0; I <4; I ++) cout <A [I] <Endl; return 0 ;}

Output result:

2 1
1
0
3
4

Why is a [1] programming 0? When using the swap function, because the parameters are all a [1], they share a memory address. When performing step a = a ^ B, at this time, the values of A and B are all zero, and the values of the second step are changed to 1, the values of the third step are all changed to 0, and the final result is 0. Therefore, this function cannot use the same address.

Related Article

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.