1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
herbNotz
  • 21
  • 7
  • They are put in different 'namespaces' or 'categories'. – user2864740 May 12 '20 at 00:27
  • The one is `struct node` and the other is `node` which will be the same thing, but with `*next;` as a self referencing member `node` isn't yet defined, so it has to be `struct node`. – Weather Vane May 12 '20 at 00:28
  • 1
    While for C++ (and thus _not_ plain C and _there are differences_), https://stackoverflow.com/a/612350/2864740 might be a nice read. It also includes links to C resources. I was not able to find a similar C-specific answer on SO quickly, although it should be possible to use such to search out. – user2864740 May 12 '20 at 00:29

1 Answers1

2

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128