Switch 2 variables and temporary variables
Let's take a look at the most common exchange method
Template
Template
Template
In SWAP1, it can be seen that the code is very concise, it is afraid of beginners, they can see its role, but because it uses a temporary variable, this means more memory, although it is still a stack. In the space SWAP2, the clever use of the different or operations to achieve the exchange of the destination code, but not a eye, it can read it, this is a lot more than swap1, but it saves A temporary variable. Although it is just a temporary variable-occupied memory, it may be very few but as a descendant, a Chinese child, and the province is the original is our virtue !!! SWAP3 is similar to swap2, just Or the operation turns into a decrease. The province is to use it is our virtue, then he will reflect the spirit of the Chinese nation on this basis.
But ..... Please take a look at our function declaration, there is a template in front, yes, this is a function template, this is C Int i, j; swapx (i, j); no matter which one, Can pass ^ _ ^ ps: swap3, don't need to consider overflow problems, why?
Let's take a look at Float F1, F2; SWAPX (F1, F2); how, do you have trouble when compiling?
Come back a struct r {long a; long b;} Rect R1, R2; SWAPX (R1, R2); this time is more trouble, only swap1 can pass
Come here, give a conclusion: From the perspective of "function template", only swap1 is qualified, because SWAP2 and SWAP3 cannot be completely converted through all types, the temporary variable becomes necessary. !! Sure enough???????, The following is the perfect solution, I don't want to say more, Template