Defining Synonymous Types Using the typedef Keyword in C++

A synonymous type can be defined using the typedef keyword.

Recall that the unsigned type is synonymous to unsigned int. C++ enables you to define custom synonymous types using the typedef keyword. Synonymous types can be used to simplify coding and avoid potential errors.

The syntax to define a new synonym for an existing data type is as follows:

typedef existingType newType;

For example, the following statement defines integer as a synonym for int:

typedef int integer;

So, now you can declare an int variable using

integer value = 40;

The typedef declaration does not create new data types. It merely creates a synonym for a data type. This feature is useful to define a pointer type name to make the program easy to read. For example, you can define a type named intPointer for int* as follows:

typedef int* intPointer;

An integer pointer variable can now be declared as follows:

intPointer p;

which is the same as

int* p;

One advantage of using a pointer type name is to avoid the errors involving missing aster­isks. If you intend to declare two pointer variables, the following declaration is wrong:

int* p1, p2;

A good way to avoid this error is to use the synonymous type intPointer as follows:

intPointer p1, p2;

With this syntax, both pi and p2 are declared as variables of the intPointer type.

Source: Liang Y. Daniel (2013),
Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *