9.7. typedef

typedef isn't much like the others, it's used to give a variable type a new name. There are two main reasons for doing this. The most common is to give a name to a struct you have defined so that you can use your new data type without having to always precede it with the struct keyword.

The second use for typedef is for compatibility. Say you want to store a 32-bit number. If you use int you are not guaranteed that it will be 32-bit on every machine. To get around this you can use preprocessor directives to selectively typedef a new type to the right size.

Example 9-2. battleships.c

#include <stdio.h>

/* type, position coordinates and armament */
struct _ship
{
  int type;
  int x;
  int y;
  int missiles;
};

typedef struct _ship ship;

int
main()
{
  ship battle_ship_1;
  ship battle_ship_2 = {1, 60, 66, 8};

  battle_ship_1.type = 63;
  battle_ship_1.x = 54;
  battle_ship_1.y = 98;
  battle_ship_1.missiles = 12;

  /* More code to actually use this data would go here */

  return 0;
}