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