best practice to handle unused variables depending on macros

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



hi,

Since gcc improves with each release, we get more, new, and better
warnings regularly. Some of these have been triggered by code such as
this:

int var = some_function_whose_return_value_is_used_only_by_assert_macro();
NS_ASSERT_MSG(var == 0, "you are screwed");

NS_ASSERT_MSG is very un-surprising:
#ifdef USE_NS_ASSERT
#define NS_ASSERT_MSG(a,b)
do {
  if ((a)) {
    // do stuff with b
  }
} while (false)
#else
#define NS_ASSERT_MSG(a,b)
#endif

Which means that our debug builds which are enabled by default work
fine while our optimized builds which do not define USE_NS_ASSERT
trigger a warning that 'var' is assigned to but unused. (and we are
good citizens and use -Werror)

Some of my collegues have started to add #ifdefs here and there in our
main code to handle these problems as they come. Others have been
advocating the use of macros that mark the problematic variables as
unused.

I dislike both: the former makes the code look really bad. The latter
creates a new macro that is going to be rarely used and that most
developers will not know about, etc. API bloat for me, more worries
down the line.

I considered adding -Wno-unused-variables but feel uneasy about it
because it is sometimes useful. I toyed with the idea of defining
NS_ASSERT_MSG differently:

#ifdef USE_NS_ASSERT
#define NS_ASSERT_MSG(a,b)
do {
  if ((a)) {
    // do stuff with b
  }
} while (false)
#else
do {
  if ((a)) {
    // do nothing with b
  }
} while (false)
#endif

Which would avoid this kind of warning but introduces two new
problems: developers are used to think that the code in NS_ASSERT_MSG
is not executed at runtime for optimized builds: this is hard to
guarantee because the assert statement could invoke arbitrary
functions located in arbitrary compilation units and the compiler
can't tell that the function has no side-effects. The other problem,
of course, happens _if_ the function has side-effects. Arguably, that
is a bug in the function being called within an assert but, life being
what it is, this is not something I feel comfortable ruling out. It
will/does likely happen.

So, I am looking for feedback on what others have done to deal with
this kind of problem. Do I need to swallow my pride and keep doing
what we have been doing ? introduce a new helper macro to mark
variables as unused ? Or is there a nice trick I am not familiar with
that would avoid all these problems ? (gcc-only solutions are
perfectly acceptable)

Mathieu
-- 
Mathieu Lacage <mathieu.lacage@xxxxxxxxx>


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux