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

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c++ - What is the meaning of `struct X typedef` vs. `typedef struct X`?

I have the following (working) code in an existing code base, used in include file that is shared between C and C++, compiling on MSVC (2010) and Windows DDK:

struct X {
    USHORT x;
} typedef X, *PX;

And:

enum MY_ENUM {
    enum_item_1,
    enum_item_2 
} typedef MY_ENUM;

As far as I know, correct definition should look like this:

typedef struct {
    USHORT x;
} X, *PX;

Is there any purpose for having the form below? Am I missing something?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The fact that both typedef <type> <alias> and <type> typedef <alias> are valid simply comes from the language grammar definition.

typedef is classified as a storage-class specfifier (just like static, auto), and the type itself is known as the type-specifier. From the syntax definitions in section 6.7 of the standard, you'll see that these are free to be interchanged:

declaration:
    declaration-specifiers init-declarator-list ;

declaration-specifiers:
    storage-class-specifier declaration-specifiers
    type-specifier declaration-specifiers
    type-qualifier declaration-specifiers
    function-specifier declaration-specifiers

init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator

init-declarator:
    declarator
    declarator = initializer

(Note, of course, that this is equally true for structs and for non-structs, meaning that double typedef trouble; is also valid.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...