Implemented in C: Swaps the contents of two values.

Source: Internet
Author: User

Many people may think that this programming problem is very simple, only need to set an intermediate variable, and then by assigning a value to complete the exchange of two values of the content.

Let's take a closer look at this simple question today:

The most basic code is as follows:

#include <stdio.h>intMain () {intA =1, B =2, T; printf ("a=%d,b=%d\n", A, b); T=A; a=b; b=t; printf ("a=%d,b=%d\n", A, b); System ("Pause"); return 0;}

But what if the title requires not to use intermediate variables to complete the above requirements?

Then we need to think about how to exchange operations using only the given variables a and b.

We can make a=a+b, when a is already the value of a and the value of B.

Once again, the b=a-b can be exchanged for B-values.

At this time A=a-b, the exchange of a value is completed.

The code is as follows:

#include <stdio.h>intMain () {intA =1, B =2; printf ("before:a=%d b=%d\n", A, b); A= A +b; b= A-b; A= A-b; printf ("after:a=%d b=%d\n", A, b); System ("Pause"); return 0;}

However, after repeated consideration, we will find that the algorithm actually has some problems.
That is, when a and B numbers are large, overflow occurs, exceeding the integer range of int.

We can then choose a third algorithm for programming, using XOR or operator programming.

The code is as follows:

#include <stdio.h>intMain () {intA =1; intb =2; printf ("before:a=%d b=%d\n", A, b); A= a^b; b= a^b; A= a^b; printf ("after:a=%d b=%d\n", A, b); System ("Pause"); return 0;}

Finally, we enclose the results of the program experiment:

Implemented in C: Swaps the contents of two values.

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.