Enforce strong type checking in C (type strictness for typedefs)

For “handle” types (opaque pointers), Microsoft uses the trick of declaring structures and then typedef’ing a pointer to the structure:

#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                             typedef struct name##__ *name

Then instead of

typedef void* FOOHANDLE;
typedef void* BARHANDLE;

They do:

DECLARE_HANDLE(FOOHANDLE);
DECLARE_HANDLE(BARHANDLE);

So now, this works:

FOOHANDLE make_foo();
BARHANDLE make_bar();
void do_bar(BARHANDLE);

FOOHANDLE foo = make_foo();  /* ok */
BARHANDLE bar = foo;         /* won't work! */
do_bar(foo);                 /* won't work! */   

Leave a Comment