A typedef merely gives a new name to an existing type or a new name for a pointer. The idea in C is to increase portability. The same applies in C++ but also is expanded to provide a long name for template specialization.
This typedef allows BYTE to be used as a type. You can change the entire body of code to use a long rather than an int just by changing the typedef.
This typedef allows you to use String as a type rather than use char*:
-
String Label = "Made in China";
-
In C for structs you can:
-
struct x
-
{
-
int month;
-
int day;
-
int year;
-
}Date;
-
-
typedef Date* DatePtr;
-
This makes Date a keyword and pDate a keyword. Now you could:
-
Date dt;
-
Dateptr pd = &dt;
-
In C without the Date keyword you have to code:
-
struct Date dt;
-
Dateptr pd = &dt;
-
so the keyword avoids having to code
struct. This is a non-issue in C++ since you don't have to code struct anyway. You would still need the typedef of Date* to DatePtr.
typedef is also used with function pointers:
-
typedef int (*Compare)(const char*, const char*);
-
This makes Compare the type for the function pointer:
Now you can use Compare in your code instead of strcmp. The advantage here is that you can change the compare function to another function just by changing the typedef.
Generally, typedef is not used with enums. An enum is a list of named integer values so all you have to do is use the named value:
-
enum Value {BLACK, RED};
-
int main()
-
{
-
int data = 20;
-
if (data == BLACK)
-
{
-
//do something
-
}
-
}
-
By using the enum as a type you can:
-
enum Value {BLACK, RED};
-
int main()
-
{
-
Value data = 20; //ERROR 20 is not a Value
-
if (data == BLACK)
-
{
-
//do something
-
}
-
}
-
prevent values other than BLACK or RED to be placed in the data variable.
Unfortunately the above examples are C++ examples and they don't work in C because in C Value is not a type. Enter the enum typedef:
-
typedef enum x{BLACK, RED} Value;
-
int main()
-
{
-
Value data = 20; //ERROR 20 is not a Value
-
if (data == BLACK)
-
{
-
//do something
-
}
-
}
-
Now Value is a type. This code can be compiled both as C or as C++.
Does this help?