Last Updated: February 25, 2016
·
820
· enno

type-safe struct wrappers

When you have two typedef's that are each implmented as the same type, you can accidentally assign from one to the other. Let's say you have two void* handles like this:

typedef void *HBITMAP;
typedef void *HWINDOW;

The compiler will not stop you from assigning a HWINDOW value to an HBITMAP variable, because to C, both are the same type. You can fix this:

typedef struct { void *ptr; } HBITMAP;
typedef struct { void *ptr; } HWINDOW;

These two types are distinct, and assignments between them are illegal. The types have the same size as before, which makes them pretty much perfect replacements.

NB: I wrote a somewhat longer version of this as an article on my blog.