8

I have code like the following in a C++ project:

struct Foo {
  union {
    double d = 1.0;
    char c;
  };
};

When I run this through Clang-Tidy, it warns me that constructor does not initialize the field c. However, when I compile the code, I do not see any warning about this union's initialization.

Does this code have a potential problem lurking? Or is the warning from Clang-Tidy a false positive that can be safely ignored?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • Hey, Can you refer to this link "https://stackoverflow.com/questions/3031605/statically-initialize-anonymous-union-in-c"? You might get some idea about your question – Senthuja Nov 13 '19 at 03:56
  • @Senthuja Btw, pro tip: you can use [ some text ]( some URL ) to create a nice link. Don't put spaces by the `[]` and `()`, though. That is purposely so it won't create a link to show you as an example. –  Nov 13 '19 at 03:58
  • 2
    This looks like a bug in clang-tidy to me. I can't see how it would even make sense to initialize multiple members of a union. – Joseph Sible-Reinstate Monica Nov 13 '19 at 03:59

1 Answers1

3

Actually, in that code, you can't initialize both variables. Check the structs and unions initialization rules. The compiler will throw something along this line Error: only one non-static data member of a union may have a default member initializer. So not only you can ignore the Clang warning, you have to in this particular case. If it's a false positive or a bug of Clang, can't say, but it clearly shouldn't be complaining about this, because fixing this warning will prevent your code from compiling.

On a more general note about these warnings. An uninitialized variable per se, won't break your program, until you try to do something that depends on the value of the variable, then many things could happen, some bad, some unknown, and some that even work fine.

By explicitly initializing the variable, you make sure it's in a consistent and known state, one which upon its use won't likely cause your program to break (unless the value you passed it made it so). Ignore these warnings at your own risk, if you really know what you're doing, or if they just don't make sense (like this one).

Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21
  • 1
    I believe you're correct about this particular warning being a false positive. However, there is an even larger issue that it is not warning about: the fact that the entire construct is dubious in C++. You can't legally type-pun like that. – Cody Gray - on strike Nov 13 '19 at 04:30