Several ways to swap the values in two variables

Source: Internet
Author: User

In the process of software development, it is often necessary to exchange the values of the two variables. There are three ways we can use the interchange method.


The first method:

int a = 3, b = 4;
int tmp;

TMP = A;
A = b;
b = tmp;

This approach is often used by the use of third variables.

The advantage is that readability is strong.

The disadvantage is that the introduction of third-party variables, high memory consumption.


The second method:

int a = 3, b = 4;

A = a + B;   A = 7; The principle is to use two numbers and a + b = Sum

b = a A; b = 7-4 = 3 B = sum-b

A = a-B;  A = 7-3 = 4; A = Sum-b

The drawback of this approach is that if the values of the two variables are very large, it will cause two variables and overflow.

The advantage is that no third-party variables are introduced to save memory.

The disadvantage is that there is a risk of data overflow, and the readability is not strong.


The third method:


int a = 3, b = 4;


A = a ^ b; The principle is to use the XOR operator

b = a ^ b; b = a ^ b ^ b = A A ^ a = 0, b ^ 0 = b

A = a ^ b; A = a ^ b ^ a = a ^ a ^ b

The advantages of this method are: No third-party variables are introduced, and memory space is saved;

There is no problem of data overflow;

The disadvantage is: The skill is strong, the readability is poor.

This article is from the "FAI Aberdeen" blog, please make sure to keep this source http://weiguozhihui.blog.51cto.com/3060615/1650435

Several ways to swap the values in two variables

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.