在C++中何时以及为什么使用预处理器宏和指令?

huangapple go评论73阅读模式
英文:

Where and why to use preprocessor macros and directives in C++?

问题

在教程中,我看到他们使用预处理指令来定义宏。为什么我应该使用宏而不是普通函数。


// 为什么我应该使用这个
#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

// 而不是这个
int GROW_CAPACITY(int capacity) {
  return capacity < 8 ? 8 : capacity * 2
}
英文:

In a tutorial I saw they used preprocessor directives to define macro. Why should I use macros instead of normal functions.


// Why should I use this
#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

// Instead of this
int GROW_CAPACITY(int capacity) {
  return capacity < 8 ? 8 : capacity * 2
}

答案1

得分: 2

在旧时代,当CPU以MHz为单位,RAM以Kb为单位时,宏始终会嵌入到代码中,使其成为简单且易读的代码的简便缩写,没有额外开销。在那些日子里,函数调用的成本可能超出了您的预期,甚至在紧密循环中可能会引起注意。在非常低功耗的设备上,也许这仍然成立。

然而,现在的CPU速度如此之快,编译器可以更多地优化函数,第二个函数可能会被内联(或者不会,编译器会知道什么时候是最佳时机),因此没有理由不使用函数。这也许是宏逐渐不再流行的原因。

然而,如果适当使用,它们仍然可以用于提高代码的可读性。即使在没有预处理器的编译器中,您仍然会看到像#if DEBUG这样的特性,这种宏非常强大,零开销。

英文:

In old times when CPUs were measured in MHz and RAM was in Kb the macro would always be inlined into code making it an easy shorthand for simple and readable code with no overhead. In those days a function call cost more than you expected or wanted and could even be noticeable in tight loops. In a very low power device maybe this is still true.

Nowadays though, CPUs are so fast the compiler can do a lot more to optimise functions, the 2nd one would be inlined (or not, the compiler will know to figure out when is best) so there's no reason not to use the function. This is perhaps why macros have fallen out of fashion.

However they can still be useful for making code more readable, if used appropriately. Even in compilers that do not have a preprocessor you still see features like #if DEBUG as this kind of macro is immensely powerful, with zero overhead.

答案2

得分: -2

两个基本原则是:

  • 如果可能的话,请使用constexpr函数或变量,
  • 如果不必要,请不要使用宏。

你应该遵循这些指导原则。

英文:

The two fundamentals principles are:

  • Use constexpr function or variable if possible,
  • Don't use macros if not necessary.

You should follow these guidelines.

huangapple
  • 本文由 发表于 2023年6月27日 17:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定