Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding unused variables warnings when using assert() in a Release build

Sometimes a local variable is used for the sole purpose of checking it in an assert(), like so -

int Result = Func(); assert( Result == 1 ); 

When compiling code in a Release build, assert()s are usually disabled, so this code may produce a warning about Result being set but never read.

A possible workaround is -

int Result = Func(); if ( Result == 1 ) {     assert( 0 ); } 

But it requires too much typing, isn't easy on the eyes and causes the condition to be always checked (yes, the compiler may optimize the check away, but still).

I'm looking for an alternative way to express this assert() in a way that wouldn't cause the warning, but still be simple to use and avoid changing the semantics of assert().

(disabling the warning using a #pragma in this region of code isn't an option, and lowering warning levels to make it go away isn't an option either...).

like image 303
Hexagon Avatar asked Apr 22 '09 13:04

Hexagon


People also ask

How do I get rid of the unused variable warning?

Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.

Does assert work in Release mode?

Because ASSERT statements are commented out in a release build of an MFC program, the code does not run in a release build.

Why is unused variable bad?

Unused variables are a waste of space in the source; a decent compiler won't create them in the object file. Unused parameters when the functions have to meet an externally imposed interface are a different problem; they can't be avoided as easily because to remove them would be to change the interface.


1 Answers

We use a macro to specifically indicate when something is unused:

#define _unused(x) ((void)(x)) 

Then in your example, you'd have:

int Result = Func(); assert( Result == 1 ); _unused( Result ); // make production build happy 

That way (a) the production build succeeds, and (b) it is obvious in the code that the variable is unused by design, not that it's just been forgotten about. This is especially helpful when parameters to a function are not used.

like image 104
Graeme Perrow Avatar answered Oct 12 '22 04:10

Graeme Perrow