22. Use of macros

Source: Internet
Author: User

------

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.