Saturday, October 1, 2011

oops

I found this nice, classic "beware of macros" bug:
#define MAX(a, b)    ((a) > (b) ? (a) : (b))
[ ... ]
int x = MAX(foo, bar++); // incremented either once or twice

Oops.

1 comment:

Siddhartha Vishvakarma said...

Macros are far less innocuous than that example pictures them. I remember someone doing something like:

#define MIN(a, b) ((a) < (b) ? (a) : (b))

int foo(int x) {
return x > 0 ? MIN(x, foo(x/2)) : 0;
}

So evaluating this function took him linear rather than logarithmic time (as it would have happened had he not used a macro).