问题
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