Using typedef

Hi all. just want to know for what and why we use "typedef" ?
i just doing some homework and I found it in example below
we have one struct named " Student" and there was one function like that

 
  typedef Student * ptrType;

and here the srudent struct :
1
2
3
4
5
6
7
8
9
10
11
  struct Student
{
   int id;
   char name[30];
   char address[30];
   char city[30];
   char state[30];
   char zip[30];
   float gpa;
   Box * next;
};

thanks





typedef is used to define an alias for an already existing type,
it's format is :
 
typedef <data_type> <alias> ;

say i want to define an alias for an unsigned int, i'll do it as follows :
 
typedef unsigned uint_t;

since it is now an alias for unsigned int, you can happily declare a variable using uint_t, and you can use it for another typedef also !
1
2
3
4
5
6
7
8
9
10
11
12
13
uint_t foo; // an unsigned integer
unsigned var; // same as the above

// now, this is something different,
// we will define an alias to a pointer to an unsigned int :
typedef uint_t* pUint_t; // pUint_t is an alias for a pointer to an unsigned
// same as
typedef unsigned* pUint_t;

// now we can declare a pointer to unsigned using pUint_t :
pUint_t pointer_to_unsigned; // a pointer to unsigned
// it is same as :
unsigned* pointer_to_unsigned


BTW, i use _t suffix to denote that it is a typedef, and a p prefix to denote that it is a pointer

~~~

so in your code, ptrType is an alias for a pointer to a Student.
1
2
3
4
5
6
7
8
typedef Student* ptrStudent;

ptrStudent student_; // remember that student_ is a pointer, NOT an object of Student
student_ = new sizeof( Student );
student_->id = 1234;
strcpy( student_->name, "John" );
// etc...
delete[] student_;


i hope this helps !
Topic archived. No new replies allowed.