call return inside GCC compound statement expressions
Asked Answered
T

2

8

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 ?

Tartary answered 17/2, 2014 at 10:3 Comment(0)
G
0

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.

Gonyea answered 17/2, 2014 at 10:22 Comment(4)
Please, can you be more specific ?Tartary
if(CHECK_FUNC_RESULT(function1)) { ... to do something } else { ... do something else } In this case, the else will not be executed. Without looking at the macro definition, this is not obvious. Otherwise, I can't find any reference pointing to an undefined behaviour when there is a return statement within the if condition. So it should work as you intend it to work, but if someone else looks at the code it can be confusing.Gonyea
But what about the topic of the question ? Is this undefined behavior or no ?Tartary
As far as I can tell, this will not result in undefined behaviour.Gonyea
T
0

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
}
Terce answered 17/2, 2014 at 11:32 Comment(1)
Your answer does not correspond with topic of questionTartary

© 2022 - 2024 — McMap. All rights reserved.