Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
Typedef pointers a good idea?

I've seen this oddity in many APIs I have used:

typedef type_t *TYPE;

My point is that declaring a variable of type TYPE will not make it clear that in fact a pointer is declared.

Do you, like me, think that this brings a lot of confusion? Is this meant to enforce encapsulation, or there are other reasons as well? Do you consider this to be a bad practice?

like image 892
Blagovest Buyukliev Avatar asked Sep 23 '10 19:09

Blagovest Buyukliev


3 Answers

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 *);
like image 140
John Marshall Avatar answered Oct 05 '22 15:10

John Marshall


A common idiom is to suffix the type with _p to indicate that it's a pointer while still retaining the pointery qualities.

Sometimes it is necessary to use only the pointer type if the struct that it is pointing to is not publicly available. This helps facilitate data hiding. I.e.

typedef struct hidden_secret_object * object;
void change_object(object foo);

this allows you to change the way that hidden_secret_object is structured without breaking external code.

like image 30
cobbal Avatar answered Oct 05 '22 15:10

cobbal


I don't find it clear either. I'm not fond of full capitalised types either (I try to reserve those for #defines).

This way makes it easy to kid oneself by thinking it is in fact a value type, while we're talking about a pointer type. The pointer type can be completely abstracted away with smart pointers, but that isn't common practise in C.

Suffixing with (as mentioned previously) _p, _ptr, Pointer or anything along those lines creates clarity; increases typing, that's true, but will prevent you from silly mistakes (such as using '.' instead of '->', ...) costing you valuable developing time.

like image 45
Taco de Wolff Avatar answered Oct 05 '22 14:10

Taco de Wolff