Philipp Claßen Philipp Claßen - 3 months ago 21
C++ Question

Is it wise to ignore gcc/clang's "-Wmissing-braces" warning?

Consider the following program:

#include <array>

int main()
{
std::array<int, 1> x = { 0 }; // warning!
x = { { 0 } }; // no warning
return 0;
}


The first initialization leads to warnings on gcc 4.7.2...

main.cpp:5:22: warning: unused variable ‘x’ [-Wunused-variable]


... and clang 3.1

main.cpp:5:28: warning: suggest braces around initialization of subobject [-Wmissing-braces]
std::array<int, 1> x = { 0 };


As far as the standard goes, there should be no difference between double or single curly braces, at least in this example.

There are two ways to deal with the warning:


  1. Just turn it off

  2. Fix the code, so the compiler is happy



What do you propose? IMHO, the double curly expression looks somewhat ugly. On the other hand, the warning might detect real problems in more complicated examples. Do you know an example where the warning would have helped you?

hvd hvd
Answer

-Wmissing-braces will no longer be enabled in GCC's -Wall (for C++ mode), as of 4.8, for precisely the reason you describe. For current versions of GCC, either disable or ignore the warning, the code you have is written the way it should be.

The warning is probably meant to cover code such as

struct A { int a; int b; };
struct B { A a; int b; };
B b = {
  1,
  2 // initialises b.a.b, not b.b
};

However, IMHO, that is already handled well enough by -Wmissing-field-initializers, which does not warn about your original code.

Comments