Reputation: 21
I've been studying singly linked lists and crossed with two different typedef struct
implementations.
1st (at CS50 lecture explanation):
// Represents a node:
typedef struct node
{
int number;
struct node *next;
}
node;
2nd (at CS50 short videos explanation):
typedef struct sllist
{
int number;
struct sllist *next;
}
sllnode;
My question is:
In the former implementation, how is the compiler able to differentiate between node
, the alias and node
, the struct
?
Why is it able to differentiate struct
from typedef
, but I cannot use the same variable name for representing int
and string
, for example?
Upvotes: 1
Views: 139
Reputation: 69367
how is the compiler able to differentiate between node, the alias and node, the struct?
Pretty easy: they are two different things. One is preceded by the struct
keyword, one is not. The typedef
can be seen as creating an alias. If the compiler sees node
alone, it looks at the typedef
to get the real type, while if it sees struct node
it already knows the type.
Why is it able to differentiate struct from typedef, but I cannot use the same variable name for representing int and string, for example?
That's a different scenario. You cannot re-define a type name that already exists. You cannot do typedef something int;
because int
already exists, the same way as you cannot do:
struct s {
int a;
};
struct s {
int a;
};
This single definition rule also applies to variable names and function names.
Upvotes: 2