1

I'm new to learning C++ and wanted some clarification on what typedef is doing in the block of code below.

typedef struct strNode Node;
struct strNode
{
  int number;   
  int weight;   
  list<Node> edges; 
};

I understand that struct strNode is creating a new datatype but what is typedef struct strNode Node doing exactly?

ameyashete
  • 27
  • 6
  • 6
    This is a C-ism. In C it lets you use `Node` instead of `struct strNode`. But in C++ you already can use `strNode` without the `struct` prefix, so the typedef is pointless (and can be shortened to `typedef strNode Node;`). – HolyBlackCat Apr 16 '22 at 07:55
  • 1
    Does this answer your question? [typedef struct vs struct definitions](https://stackoverflow.com/questions/1675351/typedef-struct-vs-struct-definitions) – 康桓瑋 Apr 16 '22 at 07:56
  • 2
    If you found this piece of code on a website that claims to be a C++ educational resource, throw that nonsensical website away and take a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – Evg Apr 16 '22 at 08:14

1 Answers1

1

what is typedef struct strNode Node doing exactly?

It's creating an alias for strNode so that you can use strNode and Node interchangeably. This setup is usually used in C to be able to use the alias within the struct definition:

typedef struct Node Node;
struct Node
{
  int number;   
  int weight;   
  Node *next;
};

This is not needed in C++. Node could here be used directly without typedef:

struct Node
{
  int number;   
  int weight;   
  std::list<Node> edges;
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108