问题
Is this declaration C99/C11 compliant ?
typedef struct element {
char *data;
struct element* next;
} element, *list, elements[5];
I could not find why it works in the standard.
回答1:
Yes, it is standard compliant. typedef declarations are like normal declarations except the identifiers declared by them become type aliases for the type of object the identifier would be if the declaration had no typedef in it.
So while
int integer, *pointer_to_integer;
declare an int object named integer and an int * object named pointer_to_integer
typedef int integer, *pointer_to_integer;
would declare an int-typed type alias named integer and an int *-typed type alias named pointer_to_integer.
From a syntactical perspective, though not functionally, typedef is just a (fake) storage classifier (like extern, auto, static, register or _Thread_local).
Your declaration
typedef struct element {
char *data;
struct element* next;
} element, *list, elements[5];
is slightly more complicated because it also defines the struct element data type but it's equivalent to:
struct element {
char *data;
struct element* next;
};
// <= definition of the `struct element` data type
// also OK if it comes after the typedefs
// (the `struct element` part of the typedef would then
// sort of forward-declare the struct )
/*the type aliases: */
typedef struct element
element, *list, elements[5];
-- it declares element as a type alias to struct element, list as a type alias to struct element * and elements as a type alias to struct element [5].
回答2:
In the C grammar, the typedef keyword acts like a storage-class specifier (like extern, static), per C 2018 6.7.1, and a type definition is simply a declaration. Like other declarations, it may have a list of declarators separated by commas (6.7 1).
The typedef in the question defines element to be an alias for the struct element type, list to be an alias for a type that is a pointer to a struct element, and elements to be an alias for a type that is an array of 5 struct element.
来源:https://stackoverflow.com/questions/57793450/use-of-comma-in-a-typedef-declaration