I'm working on a macro that will support error handling.
#define Try(e, call) ( (e == OK) && ((e = call) != OK) )
It can be used as the expression of an if-statement:
if (Try(err, SomeFunction(foo, bar))) {
// Entered only if err was OK before the if-statement and SomeFunction()
// returned a non-OK value.
}
The function won't be called if err
was already non-OK before the if-statement. After the if-statement err
will be set to the return value of SomeFunction()
.
So far so good. However I also want to use the macro without an if-statement:
Try(err, SomeFunction(foo, bar));
In this case GCC gives the following warning:
warning: value computed is not used [-Wunused-value]
And that's what my question is about: how can I rewrite the macro such that GCC won't produce this warning. I know the warning can be disabled with a flag (but I want to keep it enabled for other code) or by casting the result explicitly to void
. The following statement code won't produce the warning:
(void) Try(err, SomeFunction(foo, bar));
But it's far from ideal to prefix each Try()
with a void
cast. Any suggestions?
You can use the ternary operator like this:
( (e == OK) ? ((e = call) != OK) : (e == OK) )
I'd go for something like this
inline
bool notOK(int err) {
return err != OK;
}
#define Try(e, call) ( !notOK(e) && notOK(e = call) )
Usually compilers don't complain about function return values that are not used.
For debugging purposes it might be necessary also to add an "instantiation"
bool notOK(int err);
in a .c file.
Just an idea.
static inline int identity (int x) { return x; }
#define Try(e, call) (identity ((e == OK) && ((e = call) != OK)))
You may want to #define inline __inline__
or #define inline /*nothing*/
for non-gcc compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With