优点和使用C不同的宏功能/联方法缺点 [英] Pros and Cons of Different macro function / inline methods in C

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

问题描述

根据C FAQ ,基本上有3实用的方法为内联code在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)

要澄清这一项,参数在除权pressions使用,逗号运算符返回最后一个前pression的价值。

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

使用的是支持作为的在线声明。 HTML>扩展GCC和C99标准

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

做{...}而(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))

将preserve三元运算符的懒惰参数评测属性:只有选择的参数进行评估,而另一个则不是。一个简单的内联函数模拟将事先评估两个参数,从而做额外的不必要的工作。

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.

访问上下文。的宏可以被用来实施本地功能,即重复code片可以访问局部变量和封闭函数参数的某些相似之处。

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.

宏,我$ psented作为其利弊p $的上述特性,可能被滥用导致重大故障(因此可能是psented的利弊以及$ P $)。但是在这个时候,可以说是用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天全站免登陆