Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book


It can become tedious, repetitious, and, most important, error-prone to keep writing unsigned short int. You can create a synonym for an existing type by using the keyword typedef, which stands for type definition.

It is important to distinguish this from creating a new type (which you will do in Hour 7, "Basic Classes"). typedef is used by writing the keyword typedef followed by the existing type and then the new name. 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 Demonstrates typedef

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


Width: 5
Length: 10
Area: 50


On some compilers, this code will issue a warning that the "conversion may lose significant digits." This is because the product of the two USHORTS on line 11 might be larger than an unsigned short can hold, and assigning that product to Area can cause truncation. In this particular case, you can safely ignore this warning.

Analysis - On line 4, USHORT is typedef'd as a synonym for unsigned short int. The program is otherwise identical to Listing 3.2, and the output is the same.

  • + Share This
  • 🔖 Save To Your Account