5.14. Other Type Definitions


Use a typedef to define a new name for an existing type. For example,

  typedef unsigned int size_t;
allows you to use size_t as a name for type unsigned int, and
  typedef char* charptr;
says that charptr means the same thing as char*. Then
  charptr p,q;
makes both p and q have type charptr.

Array types

You can create a new name for an array type. Type definition
  typedef int Info[100];
indicates that a value of type Info is an array of 100 ints. Then
  Info x;
has the same effect as
  int x[100];
  Info* p = new Info;
has the same effect as
  int* p = new int[100];

Notice the similarity in structure between

  typedef char Line[80];
  char line[80];
A typedef is intended to look like a variable creation statement, but with a type substituted for the variable.

Function types

A function has a type, and you can use typedef to give a function type a name. Use a form that looks a lot like a prototype for a function, but start it with typedef and replace the function name with the function type in parentheses. For example.
  typedef int (Blue)(int,int);
defines type Blue to be the type of a function that takes a pair of ints and returns an int.

Enumerated types

An enumerated type is a type with a small number of values. Define one using enum. For example,

  enum Color {red, green, blue};
defines a new type, Color, with three values called red, green and blue. Now
  Color c = red;
creates a variable c of type Color and initializes it to red.

Values of enumerated types are represented as nonnegative integers. The values are numbered in the order that you write them, starting at 0. For example, after the definition of type Color above, red is 0, green is 1 and blue is 2.

You can list as many members of an enumerated type as you like.


  1. Define an enumerated type called Temperature that has three values, cold, mild and hot. Answer

  2. Write a C++ directive to define ValueType to be the same as double. Answer