Call back inside GCC statement

Can I safely use return inside GCC expression statement operators?

For example, I define a macro

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

and use it somewhere in the code this way:

 int function1() { if (some_condition) return 0; ... return 1; } void function2() { if(CHECK_FUNC_RESULT(function1)) { ... to do something } } 

Is it possible to expect a return from function2 (on some_condition == true) without any undefined behavior?

+6
source share
2 answers

It should work, but your if () statement will only be processed if function1 returns 1 (in your example: never). This looks like a dangerous construct, since the other will never be executed.

0
source

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

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

Usage example:

 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 } 
0
source

All Articles