The difference between a macro and a function

Source: Internet
Author: User

The difference between a macro and a function:

1, the macro does is simple string substitution, is not limited by the type, and the function is the parameter's pass, is limited by the parameter type.


2. The macro-body replacement macro name is completed before compiling, and the call to the function parameter is to pass the argument to the parameter when the function executes.


3, the substitution of macro parameters is not calculated, there may be side effects, so we write the macro body generally in the place where the parentheses can not be square brackets, but sometimes this does not solve the problem of side effects. The function is the value of the parameter simultaneous, and does not produce side effects.

 #define  MAX  (b)    ((a) > (b)? (a): (b)) Int main ( ) {                 int  a = 10;                  int b = 20;                  int ret = MAX  (a++, b++);                  printf (  "%d  %d   %d\n " , a, b, ret);                  system (  "pause");                  return 0;} 


The result is: 11 22 21

This is caused by the side effects of the macro, because the macro is the substitution of the string, and the substituted formula is: ((a++) > (b++)? (a++):(b++)). If it is a function, the value is passed, and no side effects are generated.


4, because the function is called during execution, it can be debugged, the macro is completed before compiling, so it is not possible to debug.


5, the function supports recursion, the macro does not support.


6. The function will incur the overhead of time and space when it is called, but the macro is not in the call because the macro is simply replacing the string.


7, if the use of macro comparison, macro body in the expansion will generate a lot of code, greatly reduce the running time.


This article is from the "11132019" blog, please be sure to keep this source http://11142019.blog.51cto.com/11132019/1760935

The difference between a macro and a function

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.