1
typedef struct {
int Key_value;
Node *link;
}Node;

Is the above declaration valid? or should I use

typedef struct _node{
int Key_value;
_node *link;
}Node;
tinutomson
  • 329
  • 6
  • 12

5 Answers5

4

No, it's not valid (as you would have noticed if you tried to compile it).

The typedef alias isn't introduced until the after the typedef, so you can't use it inside itself.

The second one isn't valid either (in C), _node is not a valid type name. You must use struct _node for the self-reference.

I tend to use pre-declaration and split it:

typedef struct Node Node;

struct Node {
  int Key_Value;
  Node *link;
};
unwind
  • 391,730
  • 64
  • 469
  • 606
1

The thing is that you can actually give the same name to both the structure and the typedef:

typedef struct Node {
    int Key_value;
    struct Node *link;
} Node;

Here I have added something which would have caused your code to not compile in a C compiler: The typedef isn't created until after the structure is defined. This means we must use the structure name in the link member declaration.

This can either be solved by giving the structure a name, as above, or by declaring the typedef first:

typedef struct Node *Node;

struct Node {
    int Key_value;
    Node *link;
};

Also note that in C++ you don't need to use the typedef keyword, or the struct keyword when declaring the link member:

// C++ version
struct Node {
    int Key_value;
    Node *link;
};

Structure (and class) names can be used as types in C++.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

The first declaration is invalid, because Node is not known when you declare link as a structure member. The reason is that a declaration name is visible only after the declarator (simply put, that is after a comma, equal sign, or semi-colon). So, typedef being a declaration like any other, the name Node is only visible after the final semi-colon that ends the declaration statement.

Thus, you must use the second form (the first won't even compile). However, if you're on C, note that you should prepend the struct keyword to _node, like this:

typedef struct _node {
    int Key_value;
    struct _node *link;
} Node;

This is not necessary if you're on C++.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
0

Both are invalid. Here's one valid way, for C and C++:

struct Node
{
    int Key_value;
    struct Node *link;
};


// if C, you can also do this
typedef struct Node Node;

The main point is that whatever the type of Link is, it must be something that's already been declared. The line struct X { .... declares that struct X is a type (but does not define it yet, but that's OK).

M.M
  • 138,810
  • 21
  • 208
  • 365
0

In C you should do:

typedef struct _node {
    int Key_value;
    struct _node *link;
} Node;

However, if you are using C++, it's simpler to omit the typedef at all:

struct Node {
    int Key_Value;
    Node* link;
}
Loghorn
  • 2,729
  • 17
  • 22