what is Typedef 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 given below is a replay of above given Listing, using the type definition USHORT rather than unsigned short int.

Listing : 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: }

Length: 10
Area: 50

Analysis: On line 5, USHORT is typedefined as a synonym for unsigned short int. The program is very much like previous Listing, and the output is the same.

Post a Comment