Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

gcc-warning

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?

like image 529
Bart Avatar asked Nov 02 '12 20:11

Bart


3 Answers

You can use the ternary operator like this:

( (e == OK) ? ((e = call) != OK) : (e == OK) )
like image 66
imreal Avatar answered Oct 22 '22 23:10

imreal


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.

like image 25
Jens Gustedt Avatar answered Oct 22 '22 23:10

Jens Gustedt


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.

like image 1
n. 1.8e9-where's-my-share m. Avatar answered Oct 23 '22 00:10

n. 1.8e9-where's-my-share m.