Is typedef’ing a pointer type considered bad practice? [duplicate]

In general, it’s a bad practice. The significant problem is that it does not play well with const:

typedef type_t *TYPE;
extern void set_type(TYPE t);

void foo(const TYPE mytype) {
  set_type(mytype);  // Error expected, but in fact compiles
}

In order for the author of foo() to express what they really mean, the library that provides TYPE must also provide CONST_TYPE:

typedef const type_t *CONST_TYPE;

so that foo() can have the signature void foo(CONST_TYPE mytype), and at this point we have descended into farce.

Hence a rule of thumb:

Make typedefs of structs (particularly incomplete structs), not pointers to those structs.

If the definition of the underlying struct is not to be publicly available (which is often laudable), then that encapsulation should be supplied by the struct being incomplete, rather than by inconvenient typedefs:

struct type_t;
typedef struct type_t type_t;

void set_type(type_t *);
int get_type_field(const type_t *);

Leave a Comment