How to get around GCC ‘*((void*)& b +4)’ may be used uninitialized in this function warning while using boost::optional

Paul Omta picture Paul Omta · Feb 13, 2014 · Viewed 11.5k times · Source

I have code similar to the following:

#include <boost/optional.hpp>

::boost::optional<int> getitem();

int go(int nr)
{
  boost::optional<int> a = getitem();
  boost::optional<int> b;

  if (nr > 0)
    b = nr;

  if (a != b)
    return 1;

  return 0;
}

When compiling with GCC 4.7.2 with Boost 1.53, using the following command:

g++ -c -O2 -Wall -DNDEBUG

The following warning is issued:

13:3: warning: ‘((void)& b +4)’ may be used uninitialized in this function [-Wmaybe-uninitialized]

Apparently, the root problem lies with GCC. See GCC Bugzilla Does anyone know a workaround?

Answer

Matthieu M. picture Matthieu M. · Feb 13, 2014

There are two levels of uninitialized analysis in gcc:

  • -Wuninitialized: flags variables that are certainly used uninitialized
  • -Wmaybe-uninitialized: flags variables that are potentially used uninitialized

In gcc (*), -Wall turns on both levels even though the latter has spurious warnings because the analysis is imperfect. Spurious warnings are a plague, so the simplest way to avoid them is to pass -Wno-maybe-uninitialized (after -Wall).

If you still want the warnings, but not have them cause build failure (through -Werror) you can white list them using -Wno-error=maybe-uninitialized.

(*) Clang does not activate -Wmaybe-uninitialized by default precisely because it's very imprecise and has a good number of false positives; I wish gcc followed this guideline too.