We've seen the enumeration, which is a way to create a simple type with a small number of possible values. Now we look at typedef
typedef <existing type name or definition> <new type name>;
typedef double Real; // creates the typename "Real", to stand // for type double.Perhaps on one system, type double is used most, but on another system, type float is larger and always sufficient. Then we might declare variables this way:
Real x, y, z; // x, y, z are all type double, given the // typedef above.
// enumeration definition enum cardsuit { CLUBS, DIAMONDS, HEARTS, SPADES }; enum cardsuit suit; // declaring an enumeration variableWe can use typedef on an enumeration to create a single type name, which does not require the keyword enum when declaring a variable:
typedef enum cardsuit { CLUBS, DIAMONDS, HEARTS, SPADES } CardSuit; // <--- the new type name CardSuit suit; // declaring the variableNote: In C++, this is unnecessary, because C++ takes away the need to use the keyword enum on the variable declaration. But the above example is convenient in C.
typedef enum bool {false, true} bool; // bool is now a type name, and it has // false and true as its values.
typedef int List[10]; // List is now a type that means // "10 element array of type int" List x; // x is an integer array, size 10 List y; // y is an integer array, size 10This one could come in handy when you are working with several parallel arrays, all the same size. The typedef can simplify the creation of the arrays, in a consistent manner.
Here's another example:
typedef char Name[20]; // a "Name" is a char array, size 20 // probably to be used as a string. Name first, middle, last; // three fields of size 20 each, to be // used to store different parts of names