Home > Articles

067232072x

  • Print
  • + Share This

typedef

It can become tedious, repetitious, and, most important, error-prone to keep writing unsigned short int. C++ enables you to create an alias for this phrase by using the keyword typedef, which stands for type definition.

In effect, you are creating a synonym, and it is important to distinguish this from creating a new type (which you will do on Day 6, "Object-Oriented Programming"). typedef is used by writing the keyword typedef, followed by the existing type, then the new name, and ending with a semicolon. For example,

typedef unsigned short int USHORT;

creates the new name USHORT that you can use anywhere you might have written unsigned short int. Listing 3.3 is a replay of Listing 3.2, using the type definition USHORT rather than unsigned short int.

Listing 3.3  A Demonstration of typedef

  0:  // *****************
  1:  // Demonstrates typedef keyword
  2:  #include <iostream>
  3:  
  4:  typedef unsigned short int USHORT;   //typedef defined
  5:  
  6:  int main()
  7:  {
  8:  
  9:     using std::cout;
 10:     using std::endl;
 11:  
 12:     USHORT  Width = 5;
 13:     USHORT Length;
 14:     Length = 10;
 15:     USHORT Area  = Width * Length;
 16:     cout << "Width:" << Width << "\n";
 17:     cout << "Length: "  << Length << endl;
 18:     cout << "Area: " << Area <<endl;
 19:     return 0;
 20:  }

Output

Width:5
Length: 10
Area: 50

NOTE

* indicates multiplication.

Analysis On line 4, USHORT is typedefined (some programmers say "typedef'ed") as a synonym for unsigned short int. The program is very much like Listing 3.2, and the output is the same.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.