Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding typedefing structs

Tags:

c++

struct

Please go easy on me as I'm walking a thin line here. I really searched the existing threads and I could only see statements with no examples and it just went over my head. I have been thinking whether or not to ask this for two days because I'm frankly scared to ask a silly question here. But I think I'll take the risk now and hope you go easy on me as this is my first question.

Those existent threads suggested that typedefing struct will save repeating codes, but how? Any example please? I have the following for instance:

struct Node {
    int data;
    Node* value;
};

To create a new node, I would say:

Node n1;

Even if I typedef the struct like:

typedef struct Node {
    int data;
    Node* value;
} type;

To create a new node, I would do:

type n2;

I don't really see much difference. Please provide some example that really showcases the usefulness of typedef on structs.

like image 512
Boult Avatar asked Aug 03 '26 12:08

Boult


1 Answers

For that sort of thing, a typedef is useful in C - in C++ not so much. In C, you can't just type Node when you have a struct Node - you have to actually type struct Node. So a typedef can save some typing there.

In C++ it's more useful when dealing with templated types. For example

typedef std::map<std::string, std::pair<int, std::string>> MyMap;

This lets you use e.g. MyMap::iterator instead of std::map<std::string, std::pair<int, std::string>>::iterator, which is a lot easier to type.

like image 89
Jonathan Potter Avatar answered Aug 06 '26 05:08

Jonathan Potter