本文介绍了内联函数与预处理器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内联函数与预处理器宏有何不同?

解决方案

预处理器宏只是应用于代码的替换模式。



内联函数是实际的函数,它们的主体被直接注入到它们的调用点。它们只能在函数调用合适的地方使用。



现在,就类似函数的上下文中使用宏和内联函数而言,建议: / p>


  • 宏不是类型安全的,可以扩展,不管它们是否是正确的 - 编译阶段将报告宏扩展问题

  • 宏可用于您不期望的上下文中,从而导致问题

  • 宏更灵活,

  • 由于输入表达式复制到模式中出现的任何地方,因此它们可能会因为它们的扩展而产生副作用。

  • 内联函数并不总是保证为内联函数 - 一些编译器只在发布版本中进行,或者在特殊配置时才这样做。

  • 内联函数可以为变量(尤其是静态变量)提供范围,预处理器宏只能在代码块{...}中执行,和静态变量的行为不会完全相同。


How does an inline function differ from a preprocessor macro?

解决方案

Preprocessor macros are just substitution patterns applied to your code. They can be used almost anywhere in your code because they are replaced with their expansions before any compilation starts.

Inline functions are actual functions whose body is directly injected into their call site. They can only be used where a function call is appropriate.

Now, as far as using macros vs. inline functions in a function-like context, be advised that:

  • Macros are not type safe, and can be expanded regardless of whether they are syntatically correct - the compile phase will report errors resulting from macro expansion problems.
  • Macros can be used in context where you don't expect, resulting in problems
  • Macros are more flexible, in that they can expand other macros - whereas inline functions don't necessarily do this.
  • Macros can result in side effects because of their expansion, since the input expressions are copied wherever they appear in the pattern.
  • Inline function are not always guaranteed to be inlined - some compilers only do this in release builds, or when they are specifically configured to do so. Also, in some cases inlining may not be possible.
  • Inline functions can provide scope for variables (particularly static ones), preprocessor macros can only do this in code blocks {...}, and static variables will not behave exactly the same way.

这篇关于内联函数与预处理器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:34
查看更多