1

Is the following code legal C?

#include <stdio.h>

typedef struct _BASE_STRUCT
{
    int BaseMember;
} BASE_STRUCT, *PBASE_STRUCT;

typedef struct _DERIVED_STRUCT
{
    BASE_STRUCT;    // Members belonging to this struct are "embedded" here.
    int DerivedMember;
} DERIVED_STRUCT, *PDERIVED_STRUCT;

//
// Above struct declaration is equivalent to the following, which I believe is valid
// in C11 (anonymous structs).
//
// typedef struct _DERIVED_STRUCT
// {
//     struct
//     {
//         int BaseMember;
//     };
//     int DerivedMember;
// } DERIVED_STRUCT, *PDERIVED_STRUCT;
//

int main()
{
    DERIVED_STRUCT ds;
    ds.BaseMember = 10;     // Can be accessed without additional indirection.
    ds.DerivedMember = 20;

    printf("%d\n", ds.BaseMember);

    return 0;
}

Visual Studio doesn't seem to complain about it, except for the warning about anonymous structs. However, it has the same warning for code that uses anonymous structs proper, so I assume it just hasn't been updated to be C11-conforming yet.

TripShock
  • 4,081
  • 5
  • 30
  • 39
  • 3
    No it's not really legal, because symbols with a leading underscore followed by an upper-case letter is reserved for the implementation (i.e. compiler and standard library). – Some programmer dude Aug 04 '16 at 15:49
  • 1
    @JoachimPileborg OK, let's ignore that aspect for now :). I was mainly referring to the way `BASE_STRUCT` is used. – TripShock Aug 04 '16 at 15:52
  • 1
    @dxiv only with struct { }, not if the struct is declared elsewhere and referred by name as in this example. http://stackoverflow.com/questions/23527255/is-this-a-c11-anonymous-struct – arsv Aug 04 '16 at 20:22
  • @arsv You are right, and I removed my previous comment. The posted code is illegal in `C11` because the base struct has a tag (`_BASE_STRUCT`). It's still illegal if the tag is removed (leaving `typedef struct { ... } BASE_STRUCT;`) but that's a finer point on which the `C11` drafts were not clear until nearly the end. See Keith Thompson's and Johannes Schaub's comments under [Is this a C11 anonymous struct?](http://stackoverflow.com/a/23527380) about the slight change in the definition of an `anonymous structure` between drafts N1548 vs. N1570. – dxiv Aug 04 '16 at 22:49
  • Visual Studio does not conform to any C standard well. Likely, it just compiles your code as C++, which treats structs differently than C. – Lundin Aug 19 '16 at 08:08
  • @Lundin Even though VS may not conform to a specific C standard, it certainly distinguishes between C and C++. The above code does not compile when the file extension is `.cpp`. – TripShock Aug 19 '16 at 14:30

1 Answers1

1

It's a non-standard extension, not even in C11 I think.
GCC will only accept code like that with -fms-extensions

https://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html

arsv
  • 1,176
  • 9
  • 11