0

A previous post of mine raised the topic of anonymous structs, with several commentators saying these were not allowed in C++.

Here is a construction that I use a lot: is this legal C++?

const int HeaderSize = 8192;
struct Header
{
    union
    {
        struct
        {
            int r;
            // other members
        };
        unsigned char unused[HeaderSize]; // makes Header struct's size remain constant as members are added to the inner struct
    };
    // Default constructor
    Header()
    {

    }
};
Woody20
  • 791
  • 11
  • 30

2 Answers2

1

In Standard C++ there cannot be an anonymous struct (see here for why), although mainstream compilers offer it as an extension.

I guess you intend to read binary data directly into this struct. That is frowned on in Modern C++, and it is preferred to use data serialization .

If you persist with reading directly to the struct perhaps an alternative would be:

struct Header
{
    int r;
    // other members;
};

struct Image
{
    Header hdr;
    char padding[HeaderSize - sizeof(Header)];
    // rest of image
};
M.M
  • 138,810
  • 21
  • 208
  • 365
  • Data serialization is clumsy, and I don't how it would deal with binary data. The solution you propose would have the same effect, and I don't see the advantage. – Woody20 Jul 08 '20 at 05:36
  • 2
    @Woody20 the advantage of my suggestion over yours is that it's valid code – M.M Jul 08 '20 at 05:37
  • So your answer is, the construction I showed is not valid C++? It does, however, work with my compiler (VS 2019). – Woody20 Jul 08 '20 at 05:43
  • @Woody20 I address that in the first paragraph of my answer – M.M Jul 08 '20 at 05:46
1

Anonymous structs are not a thing in C++, only anonymous unions. So you have to provide a name for the struct.

Furthermore, anonymous unions cannot have nested types either, which means you have to take the struct out of the union too.

So, combining those two bits, this means you need to write:

const int HeaderSize = 8192;
struct Header
{
    struct Members
    {
        int r;
        // other members
    };

    union
    {
        Members members;
        unsigned char unused[HeaderSize]; // makes Header struct's size remain constant as members are added to the inner struct
    };

    // Default constructor
    Header()
    {

    }
};
Acorn
  • 24,970
  • 5
  • 40
  • 69