typedef

posted Dec 1, 2014, 12:27 AM by Javad Taghia


This code sample does use typedefs:

typedef int km_per_hour ;
typedef int points ;
 
km_per_hour current_speed ;  //"km_per_hour" is synonymous with "int" here,
points high_score ;          //and thus, the compiler treats our new variables as integers.

Typedefs can also simplify declarations for pointer types. Consider this:

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

Using typedef, the above code can be rewritten like this:

typedef struct Node Node;
struct Node {
    int data;
    Node *nextptr;
};



In C++ type names can be very complicated and typedef provides a mechanism to assign a simple name to the type. Consider:

std::vector<std::pair<std::string, int> > values;
for (std::vector<std::pair<std::string, int> >::const_iterator i = values.begin(); i != values.end(); ++i)
{
   std::pair<std::string, int> const & t = *i;
   // do something
}

and

typedef std::pair<std::string, int> value_t;
typedef std::vector<value_t> values_t;
 
values_t values;
for (values_t::const_iterator i = values.begin(); i != values.end(); ++i)
{
   value_t const & t = *i;
   // do something
}


Comments