1. Macro is a replacement that is completed before compilation. 2. Macro text replacement and Typedef differences between TypedEf INT X [10] and #define x int [10] (1) can be extended with other types of specifiers, but defined by TypedF Type names can't do this.
EG,
#define peach int unsigned peach i; / * no quobem, ^ _ ^ * /
Typedef int banana; unsigned banana i; / * error, invalid, :-) * /
(2) When continuous declaration of several variables, the type defined by TypeDef can ensure that all variables in the declaration are the same type, and the type defined by #define cannot be guaranteed.
EG, #define int_ptr int * int_ptr apple, cheese;
After the macro expansion, it becomes: int * apple, cheese; makes Apple and Cheese become different types, one is the INT type pointer, the other is INT type [Reference from << c Expert Programming >> Page 68 - 69] Used for type definition This method has an advantage - portability of all C compilers. 3. With the envelope macro and function, the essence is different. For speed, the macro has the overhead of the function to call the function, it will be faster, but because the macro is only a text replace, the code is frequently used, using the macro, and the Code Size will increase. Therefore, when writing code, you should find a balance between the speed and the Code Size depending on the system environment, such as running speed, Memory Size, etc.. 4. It is best to enclose each parameter in a macro definition, and the entire result expression should also be enclosed in parentheses to prevent problems that may occur in a larger expression.
EG, #define abs (x) x> 0? x: -x
In the expression ABS (A-B), it will be deployed as
A-B> 0? A-B: -A-B The above formula will undoubtedly get a result of an error. Correct definition should be like this: #define abs (x) ((x)> = 0)? (X) :-( x)) 5. Avoid using parameters with side effects as parameters with envelope macro, such as , if is evaluated twice in macro, #define max (x, y) ((x)> ( Y)? (x): (y)) ... Biggest = max (BiggeSt, x [i ]); Departure: Biggest = ((Biggest)> (x [i ])? (Biggest) :( x [i ])) If biggest = 2, x [0] = 2, x [1] = 3, x [2] = 1, i = 1 then: i will be evaluated twice, compare I increase to 2 . If i is a function of Counter, EG,
While (i Assert_E) if (! e) assert_rror (__ file__, __line__) __file__ and __line__ is the macro in the C pre-regulator, which will be extended to the file name of the file and the line number of the line of code. If this is used: IF (x> 0 && y> 0) Assert (x> y); else assert (y> x); Departure: IF (x> 0 && y> 0) IF (! (x> y)) Assert_ERROR ("foo.c", 12); else if (! (y> x)) Assert_ERROR ("foo.c", 16) ; Randade: IF (x> 0 && y> 0) IF (! (x> y)) Assert_ERROR ("foo.c", 12); else if (! (y> x)) Assert_ERROR ("foo.c", 16) [Reference from << C Traps and Pitfalls >> Page 101 - 102] Obviously not the desired result.