开发者

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

This question already has answers here: Avoiding unused variables warnings when using assert() in a Release build (17 answers) Closed 5 years ago.

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...


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


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.


Don't know about GCC, but this has always worked in Microsoft Visual C++:

(void) success;

It references the variable without actually doing anything.


You can use a variable attribute to mark it as potentially unused.


You can utilize the NDEBUG macro, which is defined when assert are not used, for example:

#ifndef NDEBUG
  bool success =
#endif
    foo();
  assert(success);

EDIT: This will effectively "kill" the warning, as the #ifndef will ensure that there simply is no variable to warn about.


This is a slightly more concise form Lindydancer's solution at the cost of defining a helper macro. Here is the helper macro:

#ifndef NDEBUG
#  define DEBUG_ONLY( ... ) __VA_ARGS__
#else
#  define DEBUG_ONLY( ... )
#endif

Then it can be used like so:

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


You can use the GCC-specific unused attribute. It is usually defined to a short form that is easy to remove from the code for non-GCC compilers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜