GCC warning “value not used” for macro

I am working on a macro that will support error handling.

#define Try(e, call) ( (e == OK) && ((e = call) != OK) ) 

It can be used as an 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 will not be called if err already out of order before the if-statement. After if-statement err is set to the return value of SomeFunction() .

So far so good. However, I also want to use a macro without 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 is my question: how can I rewrite a macro so that GCC does not give this warning. I know that a warning can be disabled using a flag (but I want it to be enabled for other code) or by explicitly expressing the result to void . The following instruction code will not raise a warning:

 (void) Try(err, SomeFunction(foo, bar)); 

But it is far from ideal to prefix each Try() with void . Any suggestions?

+4
source share
3 answers

You can use the ternary operator as follows:

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

Remember to use e == OK (not 0) at the end, or the compiler will not accept it as an instruction.

+4
source

I would choose something like this

 inline bool notOK(int err) { return err != OK; } #define Try(e, call) ( !notOK(e) && notOK(e = call) ) 

Typically, compilers do not complain about function return values ​​that are not used.

For debugging purposes, you may also need to add an “instance”

 bool notOK(int err); 

in the .c file.

+2
source

Just an idea.

 static inline int identity (int x) { return x; } #define Try(e, call) (identity ((e == OK) && ((e = call) != OK))) 

You may want #define inline __inline__ or #define inline /*nothing*/ for compilers without gcc.

+1
source

Source: https://habr.com/ru/post/1443741/


All Articles