views:

277

answers:

4

Having a bit of internal debate in my group about the use of unnamed structs\unions in our C++ code.

I'd like to get feedback from the community of what you think. Should they be used at all? When is it valuable? What are the pitfalls? etc.

Example:

union SFlags
{
    struct
    {
        unsigned int A : 1;
        unsigned int B : 1;
        unsigned int C : 1;
        unsigned int D : 1;
    };
    unsigned int Value;
}

Edit: also consider if the original structure was defined without the union and that was added at a later point in time.

+1  A: 

In your example it's pretty cosmetic... would it REALLY hurt to name it?

flags.bits.B=1;
printf("%x",flags.Value);

In all the examples that come to mind immediately (although it is late) code would probably be clearer and easier to manage with naming. On the other hand, if your whole team is happy to check the definition of the struct every time, what does it matter?

Dave Gamble
+4  A: 

Don't use unnamed structs if you want your code to be portable. As recently as a few years back I had to name the unnamed to get some code to compile for GameCube as it was using CodeWarrior.

Otherwise, I prefer unnamed as it keeps the code more concise.

George Phillips
+1, unnamed structs are a Microsoft extension to C/C++ http://msdn.microsoft.com/en-us/library/34h23df8(VS.80).aspx . Not portable.
Adam Rosenfield
...and GCC also supports them as an extension, but it won't compile with -ansi or -std=c99 (will compile with -std=gnu89, -std=gnu99, or -std=gnu++98).
Adam Rosenfield
@Adam Rosenfield, you should have posted it as a reply, and not a comment. Very important information.
CDR
+1  A: 

Please, stick to the standards. No unnamed structs!

Norman Ramsey
+1  A: 

I consider myself pretty proficient in all things C++, but I must confess to a certain confusion over terminology. I quite often use code like this:

static const struct {
    const char * key;
    int value;
} mymap[] = {
    { "one", 1 },
    { "two", 2 },
    // ...
};

static const size_t numMyMap = sizeof mymap / sizeof *mymap;

I often call that table-driven code, and it makes changes to the table much easier later on. Now, if 'unnamed' relates to this construct, consider this a yes-vote, although I've thought of these structs as 'anonymous', not unnamed (yeah, synonyms...). They have the disadvantage that you can't use STL algorithms (or other function templates) on the table, then, but I find giving the struct a nonsense name just clutters the code.

Now, if we're talking about struct without even the 'mymap' identifier, as in the OP's union, I didn't know such beasts existed, so that's a strong indication (for me, at least) that one shouldn't use those. So, a no-vote in this case.