The Use of typedef


Enumerated data types solve some programmer needs. However there are some problems with them as was observed in the previous section. In addition sometimes all you would like to do is to use a different name (called an alias) for an already defined data type (either system or programmer defined). For this the keyword typedef may be used. The construct for using typedef to define a new data type is the following

image from book

 typedef <existing data type> <alias>; 

image from book

The major uses of typedef are to define aliases:

  • for making shorter names from longer ones

  • to use system data types with a different name

  • for renaming user defined data types

For an example of the first type: typedef was utilized in the development of Standard C++. The data type: basic_ostream was renamed ostream using typedef. In addition, the data type basic_istream was renamed istream using typedef and again, basic_string was renamed string using typedef.

The following are examples of the second use of typedef:

image from book

 typedef int Colors; typedef int Boolean; 

image from book

As a result of these two definitions, a programmer could create instances of the types: Colors or Boolean and use the properties of integers for the variables rather than having the problems that were encountered with enumerated data types. For example: see typedef1.cpp

The use of typedef for the third type will be studied after the introduction of additional programmer defined data types.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net