Are the following equivalent in C?
// #1
struct myStruct {
int id;
char value;
};
typedef struct myStruct Foo;
// #2
typedef struct {
int id;
char value;
} Foo;
If not, which one should I use and when?
(Yes, I have seen this and this.)
The second option cannot reference itself. For example:
// Works:
struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
};
// Does not work:
typedef struct {
void *value;
LinkedListNode *next;
} LinkedListNode;
// Also Works:
typedef struct LinkedListNode_ {
void *value;
struct LinkedListNode_ *next;
} LinkedListNode;
No, they're not exactly equivalent.
In the first version Foo
is a typedef for the named struct myStruct
.
In the second version, Foo
is a typedef
for an unnamed struct
.
Although both Foo
can be used in the same way in many instances there are important differences. In particular, the second version doesn't allow the use of a forward declaration to declare Foo
and the struct
it is a typedef
for whereas the first would.
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