There are many ways to exchange two-digit values in C, as described below.
Do not use intermediate variables:
1 //xor, A^=b^=a^=b;2A ^=b;3b ^=A;4A ^=b;5 6 //Add and Subtract7A = a +b;8b = A-b;9A = A-b;Ten One //multiplication AA = A *b; -b = A/b; -b = A/b;
Use intermediate variables:
1 // Temporary space required 2 temp = A; 3 a = b; 4 b = temp;
As you might think, the code shown above simply describes the idea of exchanging two-digit values, and there are many places to be aware of when you actually use them. You can choose the macro to implement, or the function is implemented, the following one by one for you.
Macro implementation:
1 #define 2 (a) ^=3 (b) ^=4 (a) ^= (b)
Note: The macro implementation is primarily for a value that does not use intermediate variables to exchange two numbers, the above code only describes the XOR, and so on.
Function implementation:
1 //Error Implementation2 voidSwapintAintb)3 {4 inttemp =0;5temp =A;6A =b;7b =temp;8 9 return;Ten } One A //Correct Implementation - voidSwapint*a,int*b) - { the inttemp =0; -temp = *A; -*a = *b; -*b =temp; + - return; +}
Note: Function implementations are applicable to using intermediate variables and not using intermediate variables.
Analysis:
Error implementation is due to a and B as the formal parameters, in the function of the exchange, but there is no effect on the external arguments, the real ability to achieve the exchange of two values is the correct implementation shown, because the parameter is two pointers, the pointer is the address, when the exchange is the value of the two address is exchanged, when the function is finished, The exchange of two values is realized.
The C language implements the value of exchanging two numbers