Chapter 18. Typedefs

The typedef specifier in C and C++ provides a new name for a given type. Two classic uses in C are in removing confusion when using function pointers and reducing typing effort when using structures. Consider the code without typedefs in Listing 18.1.

Example 18.1. 

// Info.h
struct Info
{};
int process(int (*)(struct Info*, int*), int*);

// client_code.cpp
int process_forwards(struct Info*, int);
int process_backwards(struct Info*, int);

int main()
{
  struct Info info;
  int (*pfn[10])(struct Info*, int);
  . . .
  for(i = 0; . . .; ++i)
  {
    pfn[i] = . . .

Contrast that with the code in Listing 18.2 that uses structure and function pointer typedefs.

Example 18.2. 

// Info.h
typedef struct Info {} Info_t;              // struct typedef
typedef int ...

Get Imperfect C++ Practical Solutions for Real-Life Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.