Macro definition occurs in the pre-compilation phase. Simply put, the essence is text replacement. Note the following when using it:
1. Complete brackets must be used when macro expressions are used.
For example, the following three examples:
# Define ADD (a, B) a + B
# Define ADD (a, B) (a + B)
# Define ADD (a, B) (a) + (B)
All three definitions do not meet the requirements. The traps are as follows:
When calculating ADD (a, B) * ADD (c, d), it is clear that the first problem occurs.
# Define MULTIPLE (a, B) (a * B) When computing (a + B) * c, the result returned by calling MULTIPLE (a + B, c) is incorrect.
Therefore, complete brackets must be used, as shown in the following example:
# Define ADD (a, B) (a) + (B ))
2. macro definition is used and parameter changes are not allowed. This is the difference between macro definition with parameters and functions:
The following test source code:
[Cpp]
<Span style = "font-size: 18px;" >#include <stdio. h>
# Define sqrt (a) * ())
Int fsqrt (int)
{
Return a *;
}
Int main ()
{
Int a = 10, B = 10;
Int r1, r2;
R1 = sqrt (a ++ );
R2 = fsqrt (B ++ );
Printf ("a = % d, B = % d, r1 = % d, r2 = % d \ n", a, B, r1, r2 );
Return 0;
} </Span>
The final result is a = 12; B = 11; r1 = 100; r2 = 100; The above result is obtained under vc6.0. The reason why a changes to 12 is that a ++ is executed twice during the replacement. To avoid such behavior, the macro parameter must not change.
For example: a ++; r1 = sqrt (a), everything is OK!
3. Use braces to enclose multiple expressions contained in the macro definition.
Example:
[Cpp]
<Span style = "font-size: 18px;" >#include <stdio. h>
# Define INITIAL (a, B )\
A = 0 ;\
B = 0;
Int main ()
{
Int a [5], B [5];
Int I;
For (I = 0; I <5; I ++)
INITIAL (a [I], B [I]);
Printf ("a = % d, B = % d \ n", a [0], B [0]);
Return 0;
} </Span>
It is normal to print the result of a, but printing B is not initialized. Because of simple text replacement, multiple expressions cannot be placed in the for loop. (If a variable is initialized separately, there is no problem when there is no for loop .) The macro definition above should be changed:
[Cpp]
<Span style = "font-size: 18px;"> # define INITIAL (a, B )\
{\
A = 0 ;\
B = 0 ;\
} </Span>
Note that this "\" represents the same row as the current row during pre-compilation.
Finally, let's briefly compare the differences between # define and typedef. # define occurs in the pre-compilation phase and typedef occurs in the compilation phase. For details, refer to http://topic.csdn.net/t/20030810/14/2129718.html. Let's talk about the differences in more details later.
No, I'm not sure.