Quantcast
Channel: When should I use typedef in C++? - Stack Overflow
Viewing all articles
Browse latest Browse all 14

Answer by Emiliano for When should I use typedef in C++?

$
0
0

typedef is useful in a lot of situations.

Basically it allows you to create an alias for a type. When/if you have to change the type, the rest of the code could be unchanged (this depends on the code, of course).For example let's say you want to iter on a c++ vector

vector<int> v;...for(vector<int>::const_iterator i = v->begin(); i != v.end(); i++) {// Stuff here}

In the future you may think to change the vector with a list, because the type of operations you have to do on it. Without typedef you have to change ALL occurrences of vector within your code.But if you write something like this:

typedef vector<int> my_vect;my_vect v;...for(my_vect::const_iterator i = v->begin(); i != v.end(); i++) {// Stuff here}

Now you just have to change one row of code (i.e from "typedef vector<int> my_vect" to "typedef list<int> my_vect") and everything works.

typedef also saves you time when you have complex data structures which are very long to write (and difficult to read)


Viewing all articles
Browse latest Browse all 14

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>