Typedef
From Wikipedia, the free encyclopedia
- The correct title of this article is typedef. The initial letter is shown capitalized due to technical restrictions.
typedef is a keyword in the C and C++ programming languages. It is used to give a data type a new name. The intent is to make it easier for programmers to comprehend source code.
Consider this code:
int coxes, jaffa; ... coxes++ ... if (jaffa == 10) ...
Now consider this:
typedef int Apples, Oranges; Apples coxes; Oranges jaffa; ... coxes++ ... if (jaffa == 10) ...
Both sections of code do the same thing. The use of a typedef in the second example makes it easier to comprehend what is going on, ie that one variable contains information about apples while the other contains information about oranges.
One more example:
struct var { int data1; int data2; char data3; };
Here a user defined datatype var has been defined. Thus, to create a variable of the type var, the following code is required: (Note that a struct declaration in C++ declares an implicit typedef, while in C it does not)
struct var a;
Let's add the following line to the end of this example:
struct var { int data1; int data2; char data3; }; typedef struct var newtype;
Now, in order to create a variable of type var, the following code will suffice:
newtype a;
This is much easier to read because the keyword struct does not need to precede every variable of type var.
It is also possible to declare typedefs for arrays.
typedef BaseType NewType [arrSize];
Doing this it is possible to declare a new array of type BaseType and size arrSize by writing:
NewType array;
[edit] External links
- Cprogramming.com - Detailed Discussion