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.
You can declare any type with typedef, including pointer, function, and array types. You can declare a typedef name for a pointer to a structure or union type before you define the structure or union type, as long as the definition has the same visibility as the declaration.
[edit] Explanation. If a declaration uses typedef as storage-class specifier, every declarator in it defines an identifier as an alias to the type specified. Since only one storage-class specifier is permitted in a declaration, typedef declaration cannot be static or extern.
The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
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]
.
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