"Local Scope" Macros

|
Came across some code at work today that appeared to be causing some massive compile times for a particular file. Some colleagues of mine were recording times of >5 minutes to which i sceptically replied "are you sure, sometimes i find it doesn't report files as having finished compiling and will carry on and link perfectly fine". Mr X decided to take a look at the file and narrowed down the cause to some "local scope" macros. A simple example:

void foo()
{
#define SOMETHINGCOMMON( x ) std::cout << "This is a number: " << x

SOMETHINGCOMMON( 1 )
SOMETHINGCOMMON( 2 )
SOMETHINGCOMMON( 3 )
SOMETHINGCOMMON( 4 )
SOMETHINGCOMMON( 5 )
SOMETHINGCOMMON( 6 )
SOMETHINGCOMMON( 7 )
SOMETHINGCOMMON( 8 )
SOMETHINGCOMMON( 9 )
SOMETHINGCOMMON( 10 )
SOMETHINGCOMMON( 11)
SOMETHINGCOMMON( 12 )

#undef SOMETHINGCOMMON
}


Forget for now that this is only outputting to std::cout and that the macro isn't necessarily taking an integer. What does using this method buy you that writing it as a function doesn't? It's possibly alot quicker to use and it doesn't 'clutter' any namespace. Are these important? Not half as important as the nasties that accompany using macros. It's not debuggable, it's not as readable and it's not maintainable.

The code found at work was substantially more complicated that this and involved expanding thousands of lines of more-than-one-line macro definitions. Quite why this was taking upwards of 5 minutes i don't know. Maybe it was the compiler saying, "What are you doing to me?!?!", in which case it did it's job because it was promptly changed.

Please, please avoid using these when ever you can and just use functions. It saves everyone and the compiler alot of headaches.

0 comments: