3

I'm working on some code and stumble onto something like this:

class Foo
{
private:
  union {
    byte bar;
    struct {
      byte baz1;
      byte baz2;
    };
  };
};

Now, I'm compiling with warning level 4 under VS 2010 (pure unmanaged) and of course VS complains that nameless struct/union is a nonstandard extension (warning C4201) and I want to fix that warning.

Is there ANY reason at all someone would prefer the above to:

class Foo
{
private:
  byte bar;
  byte baz1;
  byte baz2;
};

Or any reason that changing the former to the latter would break?

anthonyvd
  • 7,329
  • 4
  • 30
  • 51

3 Answers3

2

I am sure you already know this - if a union is used memory storage is shared between the members of the union. Your second example will allocate separate storage for all items but the first example will not (shared between bar and the anonymous struct).

Nameless structs /unions are not recommended in general see this URL:

Why does C++ disallow anonymous structs and unions?

I could see changing example 2 to 1 breaking, but not 1 to 2 breaking unless you are depending on the fact that the storage is shared in a union (which is VERY bad practice)..

Community
  • 1
  • 1
A B
  • 4,068
  • 1
  • 20
  • 23
1

Setting the compiler warning level to 4 will emit this warning.

Yes, there are reasons why someone would prefer a union to a struct. The two data structures are very different. I'll not go in to the reasons for or against a union here, as that's beyond the scope, but here's a link.

If you want to keep the union, you might be able to do this:

class Foo
{
private:
  union {
    int bar;
    struct {
      int baz1;
      int baz2;
    } thing_;
  };
};

Note that Foo now has a member named thing_ of type union.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
0

Sure there is a reason. Your solution requires 50% more space in memory as the version with the union. Moreover, with the union, foo.bar = foo.baz1 for all Foo foo;

marton78
  • 3,899
  • 2
  • 27
  • 38