Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct and typedef

Tags:

c

struct

typedef

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.)

like image 461
Aillyn Avatar asked Sep 22 '10 19:09

Aillyn


2 Answers

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;
like image 76
Emil H Avatar answered Oct 21 '22 16:10

Emil H


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.

like image 34
CB Bailey Avatar answered Oct 21 '22 16:10

CB Bailey