If I have these two structs:
struct
{
int x;
} A;
struct
{
int x;
} B;
then making A = B;
results in a compilation error because the two anonymous structs are not compatible.
However if I do:
typedef struct
{
int x;
} S;
S A;
S B;
A = B;
is a legal assignment because they are compatible.
But why? With typedef
I understand that the compiler makes this when meet S A
and S B
:
struct { int x; } A;
struct { int x; } B;
so A
and B
should not be compatible...
In C++, there is no difference between 'struct' and 'typedef struct' because, in C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name.
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.
In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
Each anonymous struct declaration is a distinct type; this is why you get a type mismatch when trying to assign one to the other.
A typedef, however, declares an alias (i.e. a new name for something that already exists) for a type (it does not create a new type).
A typedef is also not a simple text replacement, like a preprocessor macro. Your statement
I understand that the compiler make this when meet
S A
andS B
:struct { int x; } A; struct { int x; } B;
is where your understanding is wrong.
When you use the type alias S
, as in
S A;
S B;
the types of both objects A
and B
are the same by definition and assigning one to the other is possible.
This is because C treats every untagged struct
as a new kind of struct
, regardless of the memory layout. However, typedef struct { } name;
cannot be used if you want to use the struct
in a linked list. You'll need to stick with defining a structure tag in this case, and typedef
the tagged struct
instead.
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