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 existing datatypes new names to make a program more readable to the programmer.

Consider this code:

#include <stdio.h>
int main(void)
{
    int marks;
    marks=100;
    return 0;
}

Now consider this:

#include <stdio.h>
int main(void)
{
    typedef int student_mark_t;
    student_mark_t marks;
    marks=100;
    return 0;
}

Both sections of code do the same thing: creates an int datatype (marks) and gives it a value of 100. The method of doing this in section two makes it easier to read because the typedef statement causes student_mark_t to mean the same thing as int. In these examples, the variable marks stores the "marks" (or grades) of a student, so defining marks as a variable of type student_mark_t gives the variable name context.

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:

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

In other languages