Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With C++ and some Winapi things, I encountered this guy:

#if defined(MIDL_PASS)
typedef struct _LARGE_INTEGER {
#else // MIDL_PASS
typedef union _LARGE_INTEGER {
    struct {
        DWORD LowPart;
        LONG HighPart;
    };
    struct {
        DWORD LowPart;
        LONG HighPart;
    } u;
#endif //MIDL_PASS
    LONGLONG QuadPart;
} LARGE_INTEGER;

So, the way I see it, depending on MIDL_PASS being set or not, this is either a very compact struct with only a LONGLONG in it, or the much more interesting case, this becomes a union.

In case this is a union, it still makes sense to me, to have two possibilites of access, once the LONGLONG in one chunk, and once the struct with Low and Highpart. So far so good.

But I cannot make any sense out of the fact that the struct is declared twice, identically. It seems they are both anonymous, but the latter one is available via "u".

Now to my question:

Why are the two structs defined (redundantly?), what is the purpose of the first one, if I cannot even access it, due to not being bound to any type / variable name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
332 views
Welcome To Ask or Share your Answers For Others

1 Answer

Microsoft provides anonymous structs as an extension (their example shows one struct inside another struct, but a struct in a union is similar). If you don't mind non-portable code based on their extension, you can use things like:

LARGE_INTEGER a;
a.LowPart = 1;

but if you want portable code, you need:

a.u.LowPart = 1;

The union lets you use either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...