1. Inline function 1.1. A review of constants and macros
(1) A const constant in C + + can override the definition of a macro constant, such as:
Const int 3 ; // equivalent to #define A 3
(2) Is there a solution in C + + that can be used instead of a macro snippet?
1.2. Definition of inline functions
(1) The C + + compiler can compile a function inline, and a function that is compiled inline by the C + + compiler is called an inline function.
(2) The inline keyword is used in C + + to declare an inline function. Such as
int func (intint b) { return a < b a:b;}
(3) The inline keyword must be combined with the function definition when the inline function is declared, or the compiler ignores the inline request directly. (under vs2013, inline can be placed before declaration or definition)
1.3. Features of inline functions
(1) The C + + compiler inserts the function body of the inline function directly into the function call place
(2) The additional overhead of an inline function without a normal function call (press stack, jump, return)
(3) Inline functions are recommended for use in C + + to replace macro code snippets.
(4) The C + + compiler does not necessarily satisfy the function's inline request.
#include <stdio.h>#defineFUNC (A, B) ((a) < (b)? (a): (b))//MSVC: In order for the inline and __forceinline to take effect, the following settings must be made://① Select "Only for __inline (/OB1)" In the project → configuration properties → "C + +" → "optimize" → "inline function extensions"//② Select "Program Database (/Zi)" In "Configuration Properties" → "C + +" → "all options" → "Debug Information Format"//VS2013, the inline can be placed before the declaration or can also be placed before the definition. or both before addingInlineintFuncintAintb) {returnA < b?a:b;}intMain () {intA =1; intb =3; //int c = FUNC (++a, b);//equivalent (++a) < (b)?:( ++A):(B); //printf ("a =%d\n", a);//3//printf ("b =%d\n", b);//3//printf ("c =%d\n", c);//3 intc = Func (+ +A, B); printf ("A =%d\n", a);//2printf"B =%d\n", b);//3printf"C =%d\n", c);//2 return 0;}
The inline function is not embedded in the call place (still called by the function)
The function body is embedded in the calling place
1.4. The difference between an inline function and a macro
|
Macro |
inline functions |
Processing mode |
Processed by the preprocessor, just for simple text substitution |
Handled by the compiler, the body of the function is embedded in the calling place. But inline requests can also be rejected by the compiler |
Type check |
Do not do type checking |
Features that have normal functions are checked for parameters and return types. |
Side effects |
Yes |
No |
C + + Deep parsing Tutorial Learning notes (3) extension of functions