Title Requirement: The value of A and B are exchanged and no intermediate variables are used.
The procedure is as follows:
#include <stdio.h>
void swapValue1 (int &a, int &b)//Exchanging data with intermediate variables
{
int temp = A;
A = b;
b = temp;
}
void swapValue2 (int &a, int &b)//Use subtraction operation to complete data exchange
{
A = a + B;
b = a-b;
A = A-b;
}
void SwapValue3 (int &a, int &b)//Using bitwise operations to Exchange data
{
a^=b;
B^=a;
a^=b;
}
int main ()
{
int a1 = 1, B1 = 2;
int a2 = 3, b2 = 4;
int a3 = 5, B3 = 6;
SwapValue1 (A1, B1);
SwapValue2 (A2, B2);
SwapValue3 (A3, B3);
printf ("A=%d b=%d\n", A1, B1);
printf ("A=%d b=%d\n", A2, B2);
printf ("A=%d b=%d\n", A3, B3);
return 0;
}
Run Result:
Analytical:
The first: The use of intermediate variables to achieve the purpose of exchanging data, this is the most popular method, of course, do not meet the requirements of the subject.
The second type:
Use simple addition and subtraction operations to achieve the exchange of a, b worthwhile purposes.
Disadvantages:when A+b and A-b, it can lead to data overflow.
The third type:
using the method of bit operation, bitwise XOR OR operation. (Recommended in this way)
XOR: the same bits or operation is 0, the bits XOR is different or the operation is 1.
About the knowledge of bitwise operations, reference http://www.jb51.net/article/87880.htm
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.