Search code examples
cgccgcc-warning

Prevent GCC warning "value computed is not used" for a macro


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?


Solution

  • You can use the ternary operator like this:

    ( (e == OK) ? ((e = call) != OK) : (e == OK) )