khuang8493
11/12/2018 - 11:49 PM

use Typedef to give a shorter name for structure data types

The C keyword "typedef" provides a way to create a shorthand or rewritten name for data types. So if the original data type name are 2 words, it's a bit long and not convenient if we use it a lot. So we would use "typedef" to give it a one word shorter name.

typedef <old name> <new name>;

We can use "typedef" for the data types in C, give it a shorter name instead:

typedef unsigned char byte; // so here the original data type "unsigned char" will have a shorter name "byte". Much easier to use.

In cs50.h, we used "typedef" to define the data type "string":

typedef char* string;

Because all the custom data types have a "struct" before it, like "struct car", we often use "typedef" to give it a one word shorter name:

First we define it the normal way:

struct car
{
	int year;
	char model[10];
	char plate[7];
	int odometer;
	double engine_size;
};

Then we give it a shorter name:

typedef struct car car_t;

So now if we want to declare a new variable of this type, we can just write:

car_t mycar; // much easier

A more easier way to use "typedef" for structures is to define the new structure in the middle of "typedef":

typedef struct car
{
	int year;
	char model[10];
	char plate[7];
	int odometer;
	double engine_size;
}
car_t;