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

Posted by quinmars on Stack Overflow See other posts from Stack Overflow or by quinmars
Published on 2008-12-17T23:33:55Z Indexed on 2010/05/02 13:57 UTC
Read the original article Hit count: 278

Is there a way to enforce explicit cast for typedefs of the same type? I've to deal with utf8 and sometimes I get confused with the indices for the character count and the byte count. So it be nice to have some typedefs:


typedef unsigned int char_idx_t;
typedef unsigned int byte_idx_t;

With the addition that you need an explicit cast between them:


char_idx_t a = 0;
byte_idx_t b;

b = a; // compile warning
b = (byte_idx_t) a; // ok

I know that such a feature doesn't exist in C, but maybe you know a trick or a compiler extension (preferable gcc) that does that.

EDIT: I still don't really like the Hungarian notation in general, I couldn't used it for this problem because of project coding conventions, but I used it now in another similar case, where also the types are the same and the meanings are very similar. And I have to admit: it helps. I never would go and declare every integer with a starting "i", but as in Joel's example for overlapping types, it can be life saving.

© Stack Overflow or respective owner

Related posts about c

    Related posts about typedef