22, macro use

xiaoxiao2021-03-06  83

--------

Many programmers don't know what it means to "macro" in C? Especially when the macro has parameters, it often confuses the macros and functions. I want to talk about "macro" here, the macro is only a definition. He defines a statement block. When the program is compiled, the compiler first wants to perform a "replace" source of the source and put the macro. Replace the macro defined statement, just like text files. This action term is called "macro"

Using macro is a "danger" because you don't know what the macro will look like. For example, the macro below:

#define max (a, b) a> b? A: B

When we use macros like this, there is no problem: max (num1, num 2); because the macro is turned into Num1> Num2? Num1: Num2; However, if it is called, MAX (17 32, 25 21); , Wow, what is this?

Therefore, when the macro is in use, the parameters must be added with parentheses, and the example described above is changed to solve the problem as follows.

#define max ((a), (b)) (a)> (b)? (a) :( b)

Even so, not this macro still has bug, because if I call MAX (i , J ); after this macro, I and J have been accumulated twice, this is not what we want.

So, in the use of macro, you should also be careful, because the result of the macro show is difficult to make people expect. And though, the macro's execution is quickly (because there is no overhead of the function call), but the macro will rise to the source code, so that the target file size is large, (such as: a 50-row macro, 1000 places in the program) After the macro show will be very good after the opening), the reverse cannot make the program to perform faster (because the execution file is getting bigger, the runtime system is frequently changed).

Therefore, it is necessary to use a function when deciding is a function.

转载请注明原文地址:https://www.9cbs.com/read-107726.html

New Post(0)