- What Is a Variable?
- Defining a Variable
- Assigning Values to Variables
- Using Type Definitions
- Constants
- Summary
- Q&A
- Workshop
- Activities
Using Type Definitions
When a C++ program contains a lot of variables, it can be repetitious and error-prone to keep writing unsigned short int for each one. A shortcut for an existing type can be created with the keyword typedef, which stands for type definition.
A typedef requires typedef followed by the existing type and its new name. Here's an example:
typedef unsigned short USHORT
This statement creates a type definition named USHORT that can be used anywhere in a program in place of unsigned short. The NewRectangle program in Listing 3.3 is a rewrite of Rectangle that uses this type definition.
Listing 3.3. The Full Text of NewRectangle.cpp
1: #include <iostream> 2: 3: int main() 4: { 5: // create a type definition 6: typedef unsigned short USHORT; 7: 8: // set up width and length 9: USHORT width = 5; 10: USHORT length = 10; 11: 12: // create an unsigned short initialized with the 13: // result of multiplying width by length 14: USHORT area = width * length; 15: 16: std::cout << "Width: " << width << "\n"; 17: std::cout << "Length: " << length << "\n"; 18: std::cout << "Area: " << area << "\n"; 19: return 0; 20: }
This program has the same output as Rectangle: the values of width (5), length (10), and area (50).
On line 6, the USHORT typedef is created as a shortcut for unsigned short. A type definition substitutes the underlying definition unsigned short wherever the shortcut USHORT is used.
During Hour , "Creating Basic Classes," you learn how to create new types in C++. This is a different from creating type definitions.