在GCC复合语句表达式中调用return [英] call return inside GCC compound statement expressions
本文介绍了在GCC复合语句表达式中调用return的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我定义宏
#define CHECK_FUNC_RESULT(func)\
({\
int result = func(); \
if(!result)return; \
result; \
})
并将其用于代码中的某处这样的方式:
int function1()
{
if(some_condition)
return 0 ;
...
return 1;
}
void function2()
{
if(CHECK_FUNC_RESULT(function1)){
...做某事
}
}
我可以期望从function2(on_condition == true)返回,没有任何未定义的行为?
解决方案
一个更清晰的方法来实现你想要的,你也可以传递任何数量的参数到func(在这个例子中3 args):
#define RET_IF_ZERO(func,args)\
do {\
int result = func args; \
if(!result)\
return; \
} while(0)
使用示例:
void function1(int arg1,int arg2,int arg3)
{
if(some_condition)
return 0;
...
return 1;
}
void function2()
{
RET_IF_ZERO(function1,(arg1,arg2,arg3)));
...做某事
}
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 ?
解决方案
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
}
这篇关于在GCC复合语句表达式中调用return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文