Typedef - Using Typedef With Type Casts

Using Typedef With Type Casts

A typedef is created using type declaration syntax but can be used as if it were created using type cast syntax. (Type casting changes a data type.) For instance, in each line after the first line of:

typedef int (*funcptr)(double); // pointer to function of double returning int funcptr x = (funcptr) NULL; // C or C++ funcptr y = funcptr(NULL); // C or C++ funcptr z = static_cast(NULL); // C++ only

funcptr is used on the left-hand side to declare a variable and is used on the right-hand side to cast a value. Thus, typedefs can be used by programmers who do not wish to figure out how to convert declaration syntax to type cast syntax.

Note that, without the typedef, it is generally not possible to use declaration syntax and cast syntax interchangeably. For example:

void *p = NULL; int (*x)(double) = (int (*)(double)) p; // This is legal int (*)(double) y = (int (*)(double)) p; // Left-hand side is not legal int (*z)(double) = (int (*p)(double)); // Right-hand side is not legal

Read more about this topic:  Typedef

Famous quotes containing the words type and/or casts:

    People forget that it is the eye that makes the horizon, and the rounding mind’s eye which makes this or that man a type or representative of humanity with the name of hero or saint.
    Ralph Waldo Emerson (1803–1882)

    Christ follows Dionysus,
    Phallic and ambrosial
    Made way for macerations;
    Caliban casts out Ariel.
    Ezra Pound (1885–1972)