有一个宏定义返回一个函数值是不好的做法吗? [英] Is it bad practice to have a macro definition return a value for a function?

查看:632
本文介绍了有一个宏定义返回一个函数值是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用定义为有条件地返回值的宏有一个缺点,即仅查看客户端代码就看不到可能会在宏点退出.

Using a macro defined to conditionally return a value has a disadvantage where it is not apparent from only looking at the client code might exit at the point of the macro.

我正在考虑的用例正在编写一个值并进行错误检查,如下所示:

The use case I am considering is writing a value and error checking, like so:

#define WRITE_CHK(file, param)\
if (!write_that_returns_zero_on_fail(file, param)) {\
   handle_error();\
   return false;\
}

客户代码:

bool myfunc()
{
   ...
   WRITE_CHK(file, param) // function might return here
   ...
   return true;
}

我很好奇宏的好处(将在我的代码的许多地方使用)是否超过了上面提到的缺点. 除了简单地扩展(不使用宏)以外,还有其他替代选择吗?

I am curious if the benefits of the macro (which would be used in many places in my code) would outweigh the disadvantage mentioned above. Are there preferred alternatives besides simply expanding (not using the macro)?

推荐答案

标准答案是不要使用宏";但这通常有点简单化.有时在某些情况下,它们会大大降低您原本会拥有的样板冗长.

The standard answer is "don't use macros"; but that's often slightly simplistic. There are sometimes cases where they can greatly cut down on the boilerplate verbosity that you'd otherwise have.

那么,为什么不将事实编码为宏名称呢?例如WRITE_OR_RETURN_ON_FAILURE.它可能有点冗长,但是不太可能使您的代码阅读者绊倒.

So, why not encode the fact into the macro name? e.g. WRITE_OR_RETURN_ON_FAILURE. It may be slightly verbose, but it's much less likely to trip up readers of your code.

这篇关于有一个宏定义返回一个函数值是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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