Friday, April 8, 2005

I heart macros

How did I take so many computer science classes without finding out about this?

#define NumberFunction(number) inline static const int Return##number##() { return number; }

This C++ macro allows you to easily create functions that return a particular integer. For example, you could then use code like this:

NumberFunction(2) create two functions, Return1 and Return2, which return the integers 1 and 2 respectively. Obviously, this isn't a useful example, but it shows something cool that I didn't realize that you could do with macros—include the actual text of the macro parameter in the name of something else. I'm using this in my code to create a list of what are essentially pairs of constants both on the same value (something like ValueA and ValueB), and it really helped to simplify the code. The downside, of course, is that no one can read the code without looking at the macros first.

Macros are something that some C-lovers love, and some C-lovers abhor. I'm not by any means a C-lover, and I rather like them—they're probably the one thing from C++ that I wish I had in VB and C# and Java. BUT, there are some definite limitations to my love for macros. (1) Don't use macros to change the semantics of the language. For example, the COM macro STDMETHODIMP changes the way that you have to declare a function! That's stupid. (2) Comment your macros well; just as well as you would a function. Hopefully your macro is simple enough that this isn't even really necessary, but do it anyway. (3) Avoid using macros inside of functions. If you can use a macro inside of another function, you should probably just write an inline function instead of a macro.

But, I still don't like C++.

No comments: