What is a typedef?

So in C, apart from the struct, there is also an entity known as a typedef. typedef allows complex types to be created, and assign simple names to them. In some cases it is really creating a synonym. For example:

typedef unsigned char byte;

This creates a “new” type named byte, which is essentially an unsigned char which can contain the values 0-255. Variables of this “type” can now be defined:

byte b1, b2;

It is also possible to use a typedef to create a type from a struct. For example consider the following struct:

struct image {
    int nrow;
    int ncol;
    int pixel[700][500];
};

To create a variable from the struct image, or to define it as a parameter in a function requires the use of the clause struct in front of image, which can become tedious. For example:

struct image p;

This declares a variable p, which is an image struct. By defining a typedef we remove this restriction. Now there are a number of ways of creating them. The first is to use an existing struct, as above, and associat a typedef with it. For example:

typedef struct image photo;

This defines photo as a “type” which is a struct. Now declaring a variable p, can be done as follows:

photo p;

The second way is to associate the typedef when the struct is created. For example:

typedef struct image {
    int nrow;
    int ncol;
    int pixel[700][500];
} photo;

Now photo can be used in the same way. It is *also* possible to drop the name of the struct from the definition:

typedef struct {
    int nrow;
    int ncol;
    int pixel[700][500];
} photo;

This is useful when using structs as parameters to functions. For example, a function that prints out the data in the struct image could be defined as:

void printImage(struct image p)

or using the typedef as:

void printImage(photo p)

which is somewhat simpler.

Here’s another example:

struct bookinfo {
    char title[50];
    char author[50];
    char subject[100];
    char isbn[11];
};
typedef struct bookinfo Library[1000];

Here the struct contains information about a book. What the typedef does is create an array of structs with 1000 books, as a new “type”. We could then create a Library called cooking in the following manner:

Library cooking;

So cooking contains 1000 books.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s