Disgusting C-ism
I wrote some code that makes some assumptions about the length of int when converted to a string. This is in code that is strictly internal and is only ever called by internal code in very controlled circumstances. Still, when I wrote that assumption, it made me a little bit itchy. I asked myself a question I frequently ask, "what can I do to make sure that the compiler will catch an error for me?"
Essentially, what I wanted was to see if sizeof(int) == 4 like this:
#if sizeof(int) == 4
#error Call Steve - his assumption on sizeof(int) was wrong and this code will fail
#endif
Actually - it's better than that - the code has enough information to make it clear how to fix the code, should this arise.
I could do a runtime check wherein I count the number of bits/bytes in an int and use that, but I'd rather make this a compiler check.
I could also use:
#if MAXINT > MY_ASSUMED_MAXINT
#error Call Steve...
#endif
but I found this little gem:
#define CCASSERT(predicate) _x_CCASSERT_LINE(predicate, __LINE__)
#define _x_CCASSERT_LINE(predicate, line) \
typedef char constraint_violated_on_line_##line[2*((predicate)!=0)-1];
This defines a new type which is an array of a length that depends on the value of a predicate and will generate an illegal type on a false predicate. Nice.
the usage in my case is:
CCASSERT(sizeof(int) == 4)
which stops the compiler cold.