宏VS在C功能 [英] Macro vs Function in C

查看:117
本文介绍了宏VS在C功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C语言编程。

我在这里使用宏比使用功能较好总是看到实例和案例。

I always saw examples and cases where using a macro is better than using function.

有人能解释我用一个例子宏的缺点相比,功能?

Could someone explain me with an example the disadvantage of a macro compared to a function?

推荐答案

因为它们依赖于文本替换,不进行类型检查宏是容易出错。例如,这个宏:

Macros are error-prone because they rely on textual substitution and do not perform type-checking. For example, this macro:

#define square(a) a*a

一个整数使用时正常工作:

works fine when used with an integer:

square(5) --> 5*5 --> 25

但与前pressions使用时确实很奇怪的事情:

but does very strange things when used with expressions:

square(1+2) --> 1+2*1+2 --> 1+2+2 --> 5
square(x++) --> x++*x++ --> increments x twice

把周围的论点括号帮助,但并不能完全消除这些问题。

Putting parentheses around arguments helps but doesn't completely eliminate these problems.

当宏包含多个语句,你可以在控制流结构惹上麻烦:

When macros contain multiple statements, you can get in trouble with control-flow constructs:

#define swap(x,y) t=x; x=y; y=t;
if(x<y) swap(x,y); -->
if(x<y) t=x; x=y; y=t; --> if(x<y) { t=x; } x=y; y=t;

处理这种通常的策略是把报表内做{...}而(0)循环。

The usual strategy for fixing this is to put the statements inside a "do { ... } while(0)" loop.

如果你有这种情况发生,以包含具有相同名称但不同的语义场两种结构,相同的宏可能会在两个工作,具有奇怪的结果:

If you have two structures that happen to contain a field with the same name but different semantics, the same macro might work on both, with strange results:

struct shirt {
    int numButtons;
};

struct webpage {
    int numButtons;
};

#define num_button_holes(shirt)  ((shirt).numButtons * 4)

struct webpage page;
page.numButtons = 2;
num_button_holes(page) -> 8

最后,宏可能很难调试,生产奇怪的语法错误或运行时错误,你必须扩展到理解(例如用gcc -E),因为调试器无法通过宏步骤,因为在这个例子:

Finally, macros can be difficult to debug, producing weird syntax errors or runtime errors that you have to expand to understand (e.g. with gcc -E), because debuggers cannot step through macros, as in this example:

#define print(x, y)  printf(x y)  /* accidentally forgot comma */
print("foo %s", "bar") /* prints "foo %sbar" */

内联函数和常量有助于避免许多问题与宏,但并不总是适用的。其中,宏特意用来指定多态行为,无意多态性可能是难以避免的。 C ++有多项功能为模板,以帮助创造无需使用宏的类型安全方式复杂多态的结构,例如;见Stroustrup的的 C ++编程语言的详细信息。

这篇关于宏VS在C功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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