C++ Programming

From Wikibooks, open books for an open world
Jump to navigation Jump to search

typedef keyword is used to give a data type a new alias.

typedef existing-type new-alias;

The intent is to make it easier the use of an awkwardly labeled data type, make external code conform to the coding styles or increase the comprehension of source code as you can use typedef to create a shorter, easier-to-use name for that data type. For example:

 typedef int Apples;
 typedef int Oranges;
 Apples coxes;
 Oranges jaffa;

The syntax above is a simplification. More generally, after the word "typedef", the syntax looks exactly like what you would do to declare a variable of the existing type with the variable name of the new type name. Therefore, for more complicated types, the new type name might be in the middle of the syntax for the existing type. For example:

 typedef char (*pa)[3]; // "pa" is now a type for a pointer to an array of 3 chars
 typedef int (*pf)(float); // "pf" is now a type for a pointer to a function which
                           // takes 1 float argument and returns an int

This keyword also covered in the Coding style conventions Section.

Note:
You will only need to redeclare a typedef, if you want to redefine the same keyword.