Documenting which methods are more pervasive and more efficient does not include methods that use functions, and using pointers is more appropriate if you use functions.
- Using intermediate variables
Shaped as int tmp, TMP = A; A=b; b = tmp;
1 #define SWAP (A, b) {typeof(a) _t=A; A=B; b=_t;}
The only drawback is the need for additional stack space.
1 #define SWAP (x, y) (x) = (x) + (y); (y) = (x)-(y);(x) = (x)-(y);
cannot be used, x+y can cause data overflow, then it is finished, and can only operate on basic data types, construction data types cannot be used.
- The cost of brain-different or law
1 #define SWAP (x, y) (x) ^= (y); (y) ^= (x);(x) ^= (y);
Can only be manipulated for basic data types and cannot be used for construction data types.
Then compare the efficiency of 1,3, using 2 macros to run the following code:
int Main (intconstChar *argv[]) { int0xFFFFFFF ; int 5 ; int Ten ; while (k-- ) { SWAP (A, b); } return 0 ;}
Using time./main timing, the Xor method takes 2.2-2.4s, the intermediate variable method time 0.7-0.8s, the efficiency increases 3 times times.
C language uses macros to implement exchange of 2 variables