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?
Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
typedef in C++ typedef keyword is used to assign a new name to any existing data-type. For example, if we want to declare some variables of type unsigned int, we have to write unsigned int in a program and it can be quite hectic for some of us.
You can't "typedef a struct", that doesn't mean anything.
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.)
As others said, typedef
is a storage-class specifier and as with other storage-class specifiers you are also allowed to put the specifier between the type and the declarator.
While this is valid and it is also a form that should be avoided as C marked it as an obsolescent feature:
(C11, 6.11.5p1) "The placement of a storage-class specifier other than at the beginning of the declaration specifiers in a declaration is an obsolescent feature."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With