Four Methods for swap (a, B) value exchange

Source: Internet
Author: User

The content to be described in this article is indeed very simple. Before I wrote it, I had to worry about it for a long time: writing or not writing. We usually use the first method for swap (a, B) value exchange. For people with better mathematics, we may think of the second method. At that time, we must feel good ,. People who have an understanding of assembly or counterpoint may think of the third method. This method is very good. However, the fourth method that prompted me to write this article is wonderful. It is really amazing. First (B = a), I did not expect it. I think, such a good thing, although simple, it is worth sharing. Swap (a, B) value exchange methods: [cpp] void swap (int & a, int & B) {// Method 1: int tmp = 0; tmp = B; B = a; a = tmp; // Method 2: // a = a + B; // B = a-B; // a = a-B; // method 3: // a ^ = B ^ = a ^ = B; // Method 4: // a = a + B-(B = a);} int main (void) {int a = 3; int B = 4; printf ("before swap: a = % d, B = % d \ n ", a, B); swap (a, B); printf (" after swap: a = % d, B = % d \ n ", a, B); return 0;} result: before swap: a = 3, B = 4 after swap: a = 4, B = 3 There are three methods for passing parameters: Value passing parameters, address passing parameters, and reference passing parameters (C ++ method). The preceding method uses the third method, this method makes swap more intuitive. Of course, you can also use the second parameter passing method to transmit parameters. However, parameter passing by value does not work.

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.