有这个宏的问题 - 检查状态,如果失败则返回 [英] are there problems with this macro - check status and return if failed

查看:120
本文介绍了有这个宏的问题 - 检查状态,如果失败则返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在代码中有一个经常重复出现的行,用于检查函数的返回状态,如果它是一个失败返回的状态立即。我想为这个定义一个宏:

we have a frequently recurring lines in the code that check for the return status of a function, and if it's a failure return with the status immediately. I thought of defining a macro for this:

#define RETURN_IF_FAILED(x) { int stat = (x); if (FAILED(stat)) return stat; }

局部变量是因为参数 x 可以是一个函数调用。

The local variable is because the parameter x could be a function call.

因为我知道有一些奇怪的使用宏的工件,我不是很熟练他们,我想问,如果你看到这个宏的任何问题。谢谢。

As I know there are some weird artifacts of using macros and I am not very proficient in them, I'd like to ask if you see any problems with this macro. Thanks.

(请不要建议使用例外 - 我自己讨厌这种风格,但这是这样做的)

(and please, don't suggest to use exceptions - I hate this style myself, but that's the way it's done here)

推荐答案

我想修改一下;它包含 do {} while(0)像这样:

I would like to modify it a bit; enclosing it with do{} while(0) like this:

#define RETURN_IF_FAILED(x) do { int stat = (x); if (FAILED(stat)) return stat; } while(0)

现在你可以使用这个宏,如下:

Now you can use this MACRO, like this:

if (SomeCondition)
  RETURN_IF_FAILED(x); //<--- note the "usual" semicolon!
else
{
   //some code
}

对于你的版本,这个代码是不可能的。宏后的; 会导致您的版本出现问题!

With your version, this code is NOT possible at all. The ; after the macro would cause problem in your version!

这篇关于有这个宏的问题 - 检查状态,如果失败则返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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