call return inside GCC compound statement expressions

空扰寡人 提交于 2019-12-23 09:26:24

问题


Can I safely use return inside GCC compound statement expressions ?

For example I define macro

#define CHECK_FUNC_RESULT(func)    \
({                                 \
   int result = func();            \
   if (!result) return;            \
   result;                         \
})

and use it somewhere in code in such way:

int function1() 
{
   if (some_condition) 
     return 0;
   ...
   return 1; 
}

void function2()
{
   if(CHECK_FUNC_RESULT(function1)) {
      ... to do something
   }
}

Can I expect returning from function2 (on some_condition == true) without any undefined behavior ?


回答1:


It should work, but your if() statement will only be processed if function1 returns 1 (in your example: never). This looks like a dangerous construction, as an else would never be executed.




回答2:


A cleaner way to achieve what you want, and you can also pass any number of arguments to func (in this example 3 args):

#define RET_IF_ZERO(func, args) \
do {                            \
    int result = func args;     \
    if (!result)                \
        return;                 \
} while (0)

Example of usage:

void function1(int arg1, int arg2, int arg3)
{
    if (some_condition) 
        return 0;
    ...
    return 1;
}

void function2()
{
   RET_IF_ZERO(function1, (arg1, arg2, arg3)));

   ... do to something
}


来源:https://stackoverflow.com/questions/21825943/call-return-inside-gcc-compound-statement-expressions

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