[C/C++] inline keyword inline

inline keyword

The code of an inline function will be expanded by the compiler at the place where it is called.

Solve the problem that some frequently called small functions consume a lot of stack space (stack memory).

1. Function

  • Save stack space and prevent insufficient stack space
  • Reduce stack operations generated by function calls and improve program execution efficiency

2. Precautions

  • Whether the function modified by inline can be truly inlined (expanded at the call site) is determined by the compiler. If the function body is too large after expansion, the compiler may not expand it.
  • inline is only suitable for relatively simple functions, and cannot contain complex structure control statements while and switch
  • inline must be placed together with the definition of the function body to achieve inlining
  • The implementation of inline functions should be placed in the header file. Otherwise, the inline function definition needs to be rewritten when called by other source files.
  • inline can improve execution efficiency, but at the expense of code size

3. The difference from #define

The macro function defined by #define is implemented by the preprocessor, and there is no parameter push and code generation, which is very efficient.

When define is used, it is only a simple replacement, and the validity of the parameters cannot be checked . The return value is the value of the last expression and cannot be cast to a suitable type.

The inline function is a real function, and the compiler will check the correctness of the parameter type when calling it.

4. inline recursive function

inline generally does not modify recursive functions.

If you inline a recursive function, the compiler may not expand at the call site, or expand to a certain depth. But this situation needs to be avoided.

Guess you like

Origin blog.csdn.net/weixin_45636061/article/details/125007723