------
ManyProgramThe clerk does not know what the "macro" in C really means? In particular, macros and functions are often confused when they have parameters. Here I want to talk about "macros". macros are just a definition. They define a statement block. When the program is compiled, the compiler must first execute an action to replace the source program and replace the macro reference with the macro-defined statement block, just like replacing a text file. This action term is "macro expansion"
It is dangerous to use macros because you do not know what the macros will look like after they are expanded. For example, the following macro:
# Define max (A, B) A> B? A: B
When we use macros like this, there is no problem: max (num1, num2); because the macro is expanded to num1> num2? Num1: num2 ;. However, if it is called in this way, Max (17 + 32, 25 + 21); and an error occurs during compilation because the macro is expanded: 17 + 32> 25 + 21? 17 + 32: 25 + 21. Wow, what is this?
Therefore, when using a macro, you must add brackets to the parameters. The example above is changed to the following to solve the problem.
# Define max (a), (B) (a)> (B )? (A) :( B)
Even so, there is still a bug in this macro, because if I call Max (I ++, J ++) like this; after this macro, I and J have been accumulated twice. This is definitely not what we want.
Therefore, you should be careful when using macros, because the results of macro development are very unpredictable. In addition, although macro execution is fast (because there is no overhead for function calling ),Source codeThe growth rate increases the size of the target file (for example, a 50-line macro is used in 1000 places in the program, and the macro size will be very bad after expansion ), on the contrary, the program cannot be executed faster (because the execution file becomes larger and the system frequently changes pages during running ).
Therefore, be careful when deciding whether to use a function or a macro.