are there problems with this macro - check status and return if failed

核能气质少年 提交于 2020-01-13 18:10:51

问题


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; }

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)


回答1:


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!



来源:https://stackoverflow.com/questions/4615171/are-there-problems-with-this-macro-check-status-and-return-if-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!