Typedef Keyword in C++

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. 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. A demonstration of typedef.

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

Output: Width:5
Length: 10
Area: 50

Analysis: On line 5, USHORT is typedefined as a synonym for unsigned short int. The program is very much like Listing 3.2, and the output is the same.
Typedef Keyword in C++ Reviewed by 1000sourcecodes on 20:42 Rating: 5
Powered by Blogger.