Typedefs

User-defined types (revisited):

The three common ways of defining your own types (or type names) in C:
  1. typedef
  2. enum (enumeration)
  3. struct

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

A typedef statement creates a synonym (or alias) for previously defined types.

Some reasons to create a typedef

Format

  typedef <existing type name or definition> <new type name>;

Examples

Using a typedef on simple types

  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.

Using a typedef on an enumeration

We know that this is legal:
  // enumeration definition
  enum cardsuit { CLUBS, DIAMONDS, HEARTS, SPADES };

  enum cardsuit suit;		// declaring an enumeration variable
We 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 variable
Note: 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.
 

Creating a bool type

Like in C++
  typedef enum bool
  {false, true} bool;		// bool is now a type name, and it has
				//  false and true as its values.

Using a typedef on an array

  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 10
This 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

Using typedef with structures

There is another C construct known as a struct, which is short for "structure". In C, typedefs are sometimes used with structures as well. We will probably see some examples of this when we cover struct, later in the course.