The difference between inline and macro definition

Macro definition

The keyword define .
1. Define commonly used constant quantities. Such as:

#define PI 3.14

2. Define small functions. Such as:

#define product(x)    x*x

3. Prevent header files from being repeatedly included

#ifndef CODE_H	
#define CODE_H
/**
 * 
 */
#endif

! ! ! Precautions! ! !
The essence of macro definition is just simple text replacement, which occurs in the preprocessing stage! ! !
So if there are the following definitions:

#define product(x) x+x

Then use as product(1) * product(1) and the result is: 1+1 * 1+1 = 3;
instead of 2 * 2=4;

Inline function

The keyword inline .
Inline is a product of C++ used to replace macro definitions. What can I do by adding inline before the function?
! ! ! Precautions! ! !
1. It is just a suggestion to the compiler. If the function is too complicated, such as self-recursion, it will not be optimized.
2. It is a real function, put into the symbol table when compiling, and then directly perform code replacement and expansion when calling.
3. At the compiling stage , copy the code to the designated area.

Advantages: Save the cost of function calls.
Disadvantages: not too much code can be copied in at the same time, which will cause code bloat.

! ! ! important! ! !
The member function of the class defaults to inline, inline defaults to the static link attribute, and other files cannot find it in the symbol table. Then it will not cause a redefinition error.

the difference

1. The macro definition will not judge the type, but only the replacement text stored separately;
inline will judge the parameter type.
2. A macro is not a function, and what inline modifies is a function.
3. The macro return value cannot be coerced into an appropriate type, but the inline return value can be.

Guess you like

Origin blog.csdn.net/weixin_45146520/article/details/114392525