什么时候应该使用宏而不是内联函数? [英] When should you use macros instead of inline functions?

查看:127
本文介绍了什么时候应该使用宏而不是内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在之前的问题我认为是个好答案,但由于建议使用宏而被否决了

In a previous question what I thought was a good answer was voted down for the suggested use of macros

#define radian2degree(a) (a * 57.295779513082)
#define degree2radian(a) (a * 0.017453292519)

代替内联函数.请原谅新手问题,但是在这种情况下,宏到底有什么弊端?

instead of inline functions. Please excuse the newbie question, but what is so evil about macros in this case?

推荐答案

关于宏,有一些严格的邪恶规定.

There's a couple of strictly evil things about macros.

它们是文本处理程序,没有作用域.如果您 #define foo 1 ,则随后任何将 foo 用作标识符的操作都会失败.这可能会导致奇怪的编译错误和难以发现的运行时错误.

They're text processing, and aren't scoped. If you #define foo 1, then any subsequent use of foo as an identifier will fail. This can lead to odd compilation errors and hard-to-find runtime bugs.

他们不接受一般意义上的争论.您可以编写一个将接受两个 int 值并返回最大值的函数,因为参数将被评估一次,之后将使用这些值.您无法编写宏来执行此操作,因为它将至少对两次参数求值两次,并且失败,并出现诸如 max(x ++,--y)之类的错误.

They don't take arguments in the normal sense. You can write a function that will take two int values and return the maximum, because the arguments will be evaluated once and the values used thereafter. You can't write a macro to do that, because it will evaluate at least one argument twice, and fail with something like max(x++, --y).

还有一些常见的陷阱.很难在其中正确地获得多个语句,并且它们需要很多可能多余的括号.

There's also common pitfalls. It's hard to get multiple statements right in them, and they require a lot of possibly superfluous parentheses.

在您的情况下,需要括号:

In your case, you need parentheses:

#define radian2degree(a) (a * 57.295779513082)

需要成为

#define radian2degree(a) ((a) * 57.295779513082)

并且您仍在踩在内部范围内编写函数 radian2degree 的任何人,并确信该定义将在其自己的范围内起作用.

and you're still stepping on anybody who writes a function radian2degree in some inner scope, confident that that definition will work in its own scope.

这篇关于什么时候应该使用宏而不是内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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