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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With