Here's a bug that bit me recently. I wrote a very small quick and dirty TDD header for C in my
CyberDojo. It has a macro called CHECK_EQ which you use as follows:
CHECK_EQ(int, 42, 9*6);
Part of the macro looks like this:
#define CHECK_EQ(type, expected, actual) \
... \
type e = expected; \
type a = actual; \
... \
Can you see the problem? Well, suppose it's used like this:
int e = 42;
CHECK_EQ(int, e, 9*6);
Can you see it now? The problem is that this line in the macro
type e = expected; \
gets expanded into this line:
type e = e; \
Ooops. I thought about choosing a very cryptic name instead of x. Perhaps incorporating __LINE__ as a suffix. But I felt there had to be a solution that would
always work. After some thought I came up with this. Brace yourself...
#define CHECK_EQ(type, expected, actual) \
...
if (#expected[0] != 'x') \
{ \
type x0 = expected; \
type x1 = actual; \
... \
} \
else \
{ \
type y0 = expected; \
type y1 = actual; \
... \
} \
...
Like
Tom Duff, I feel a mixture of pride and revulsion at this discovery.