Difference between macro and function.

macro
1. When calling a macro, the parameters are first checked to see if they contain any symbols defined by #define. If so, they are replaced first;
2. The replacement text is then inserted into the program in place of the original text. For macros, parameter names are replaced by their values;
3. Finally, scan the resulting file again to see if it contains any symbols defined by #define. If so, repeat the above process.
However, there are a few caveats when defining macros:
1. Macro parameters and #define can appear in the definition of other #define-defined variables. But for macros, recursion cannot occur;
2. When the preprocessor searches for symbols defined by #define, the contents of string constants are not searched.

The macro is executed before compilation, that is, the macro name is replaced with the macro body first, and then compiled, and the function is obviously called after compilation and when it is executed. Therefore, the macro takes up the compilation time, and the function takes up Execution time.
I:
   The parameters of the macro do not occupy memory space, because it is only a string replacement, and the parameter transfer when the function is called is the information transfer between specific variables, and the formal parameters are used as local variables of the function. Apparently it takes up memory

Code Length Macro code is inserted into the program
every time it is used, except for very small macros, the length of the program will grow substantially
Function code only appears in one place, each time it is used, the same one in that place is called low Code
Execution speed
Faster 
function call returns with additional time
overhead Operator precedence
Macro arguments are evaluated in the context of all surrounding expressions, unless they are parenthesized, the precedence of adjacent operators may be unpredictable the result of. A function parameter is evaluated only once when the function is called, and its result value is passed to
the function. The result of evaluating the expression is more predictable
. Parameter Evaluation
Evaluated, parameters with side effects may produce unpredictable results
Function parameters are only evaluated once when the function is called, and multiple use of parameters in a function does not result in multiple evaluations. The side effects of parameters do not cause any special problems.
Parameter types
Macros are type independent, as long as the operation on the parameter is legal, it can use any parameter type. The parameters of the
function are related to the type, if the parameters are of different types, you need to Use different functions even if they perform the same task

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324805007&siteId=291194637