3

If I want to make a variable Point which can hold 2 doubles and I want to avoid having to write struct everytime I use it I can simply use:

typedef struct{
    double x,y; 
}Point;

But when I want to make a linked list the declaration must be like this:

typedef struct Node Node; // (2)
struct Node{
    int d;
    struct Node * next;   
};

And not like this:

typedef struct{
    int d;
    struct Node * next;   
}Node;

Why does the declaration have to be this way and why do you have to type "Node" twice, see (2).

3
  • It only has be like that (2) when your declared structure uses Node *next; (which yours does not). You can just use struct Node. Or is the intent to declare the Node type in the first place? Commented Aug 19, 2015 at 18:20
  • What is the relation between Point and Node? Update, oh, it's just an example, right? Commented Aug 19, 2015 at 18:22
  • Your third option can work, if you give the struct a tag: typedef struct Node{ int d; struct Node * next; } Node; Commented Aug 19, 2015 at 18:24

1 Answer 1

1
typedef struct Node Node;

This statement is the directive to the compiler to consider Node to be the same name as struct Node, that is why it has to include the word "Node" twice.

Also the declaration doesn't have to be this way, the second version is correct too.

The struct declaration doesn't have to include typedef at all, it is needed only to assign the type a new name and is often used with struct declarations to avoid the need to type the word struct over and over.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.