Instructions for using C++ inline functions (the difference between macro definitions)


The inline function is based on inline Keyword-modified functions, C++ will expand at the place where the inline function is called when compiling, without the overhead of function pushing on the stack, it is a kind of Space for time Ways to improve the efficiency of program operation.

Inline function call rules

1. Inline function is a suggestion, the compiler automatically optimizes, choose whether a function containing the inline keyword will be used as an inline function. The function body defined as inline has recursion or loop, and the compiler ignores inline by default. Generally, the function code is small, and frequently called as inline functions.

Notes on inline functions

2. It is not recommended to separate the definition and declaration of inline functions, and an error will be reported when linking. The compiler cannot find the address of the inline function at link time. as follows:

//pt.h
#include <iostream>
using namespace std;
inline void pt(int i);
// pt.cpp
#include "pt.h"
void pt(int i)
{
    
    
	cout << hello << endl;
}
// main.cpp
#include "pt.h"
int main()
{
    
    
	pt(10);
	return 0;
}

Insert picture description here

The difference between inline function and macro definition

3. Inline functions are roughly the same as macros. They are both replacements, except that inline functions are safer, with more syntax and type checking. Inline functions are essentially functions.
Insert picture description here

Insert picture description here
It's because macros are the simplest replacement:
unless:
Insert picture description here

Although it is useful to add parentheses, you have to write more complicated logic yourself when faced with complex ones.
Let's use the inline function to see: in
Insert picture description hereone step. So inline functions are better to use than macros.

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/113638553