Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert and unused local variable warning in GCC don't mix well? [duplicate]

Tags:

c++

c

gcc

g++

I have a problem with the unused local variable warning in GCC.

Often I have code that looks like this:

bool success = foo();
assert(success);

This is fine for debug builds. In release however, the assert compiles to nothing, and GCC gives me a warning.

What is the best way to work around this? Wrapping the bool success = with #ifdef just does not seem like a nice solution...

like image 677
Johan Kotlinski Avatar asked Apr 11 '11 19:04

Johan Kotlinski


2 Answers

I would probably define a macro specific to this scenario

#ifndef NDEBUG
#define verify(expression) assert(expression)
#else
#define verify(expression) expression
#endif

I prefer this approach over using a local variable because it doesn't pollute the method with values that only conditionally exist.

In general I find it very helpful to have 2 sets of macros in my projects

  • assertXXX: debug only execution
  • verifyXXX: retail + debug execution
like image 51
JaredPar Avatar answered Oct 13 '22 20:10

JaredPar


I use a macro

#define UNUSED(x) ((void)(x))

used like so:

UNUSED(success);

macro to silence the warning and to document that the fact that the variable is unused (at least at in some builds) is intentional/ok.

like image 43
Michael Burr Avatar answered Oct 13 '22 19:10

Michael Burr