typedef -- standard in C/C++. Used to assign a more meaningfull or appropriate name to a variable type. For instance you may be using int's as booleans, so why not declare them as booleans?

typedef old type new type;
typedef int bool;
typedef float dollars;
typedef struct box_t BoxDim;

now you can declare:
bool
bHouseOnFire;
dollars
dPrice;
BoxDim
bMyBox;

Typedef is a language construct in C and therefore also in C++.
It has two main purposes:

  • To name a complicated (composite) type with a simpler name
  • To hide an implementation detail from other parts of implementation - as a handle where the actual type can easily be changed.

The last is especially important in C++ typedef, where a typedef can be a class member.

In most cases, typedef's use could be easily replaced by a #define. However, it allows the use of standard declaration and greater flexibility in more complicated cases.

With typedef, you can create types that are arrays, which would be unwieldy to do with #define:
    typedef int arrayType[5];
    arrayType array1;
As opposed to:
    #define arrayMacro(var) int var [5]
    arrayMacro(array2);

Another difference is scope - in gcc, typedefs defined in a function are not valid outside a function. However, a #define will be valid from the point of its definition to the end of the file.
In Microsoft Visual C++, you cannot define a typedef inside a function.

Also, typedefs and variables can have identical names. This could lead to some confusion for others trying to read the code, though.

Log in or register to write something here or to contact authors.