C中不同宏函数/内联方法的优缺点 [英] Pros and Cons of Different macro function / inline methods in C

查看:20
本文介绍了C中不同宏函数/内联方法的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据C FAQ,内联"基本有3种实用方法C中的代码:

According to the C FAQ, there are basically 3 practical methods for "inlining" code in C:

#define MACRO(arg1, arg2) do { 
    /* declarations */ 
    stmt1;   
    stmt2;   
    /* ... */  
    } while(0)    /* (no trailing ; ) */

#define FUNC(arg1, arg2) (expr1, expr2, expr3)

为了澄清这一点,表达式中使用了参数,逗号运算符返回最后一个表达式的值.

To clarify this one, the arguments are used in the expressions, and the comma operator returns the value of the last expression.

使用 inline 声明,该声明被支持为 对 gcc 和 c99 标准的扩展.

using the inline declaration which is supported as an extension to gcc and in the c99 standard.

do { ... } while (0) 方法在 Linux 内核中被广泛使用,但我没有经常遇到其他两种方法.

The do { ... } while (0) method is widely used in the Linux kernel, but I haven't encountered the other two methods very often if at all.

我指的是多语句函数",而不是像 MAX 或 MIN 这样的单语句.

I'm referring specifically to multi-statement "functions", not single statement ones like MAX or MIN.

每种方法的优缺点是什么,为什么在各种情况下您会选择其中一种?

What are the pros and cons of each method, and why would you choose one over the other in various situations?

推荐答案

说到宏的具体用途,即充当函数"的宏,我要提一下宏所不能具备的以下优点内联函数:

Talking about that specific use of macros, i.e. macros that act as "functions", I'd mention the following advantages of macros that can't be had in an inline function:

惰性参数求值.例如,像这样的宏

#define SELECT(f, a, b) ((f) ? (a) : (b))

将保留三元运算符的惰性参数求值属性:仅对选定参数求值,而另一个不求值.一个简单的内联函数类比会提前评估这两个参数,从而做额外的不必要的工作.

would preserve the lazy argument evaluation properties of the ternary operator: only the selected parameter is evaluated, while the other is not. A straightforward inline-function analogue would evaluate both arguments in advance, thus doing the extra unnecessary work.

访问上下文. 宏可用于实现局部函数"的一些相似之处,即可以访问封闭函数的局部变量和参数的重复代码片段.

Access to context. Macros can be used to implement some resemblance of "local functions", i.e. repetitive pieces of code that have access to the local variable and parameters of the enclosing function.

类型独立(和类型参数). 宏允许您编写类型独立的函数"(参见上面的示例).如果你无法摆脱类型依赖,你可以将类型作为参数传递给宏.

Type independence (and type parameters). Macros allow you to write type-independent "functions" (see above example). And in case you can't get rid of type-dependence, you can pass types as parameters to the macro.

宏的上述属性,我作为它们的优点,可能会被滥用而导致重大故障(因此也可以作为缺点来表示).但这就是 C 语言中许多语言特性的特点.

The above properties of the macros, which I presented as their pros, could be misused to lead to major failures (and thus could be presented as cons as well). But that's something that can be said of many language features in C.

这篇关于C中不同宏函数/内联方法的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆