When are C++ macros beneficial? [closed]

The C preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a #define.

The following macro:

#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)  

is in no way superior to the type safe:

inline bool succeeded(int hr) { return hr >= 0; }

But macros do have their place, please list the uses you find for macros that you can't do without the preprocessor.

Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.


As wrappers for debug functions, to automatically pass things like __FILE__, __LINE__, etc:

#ifdef ( DEBUG )
#define M_DebugLog( msg )  std::cout << __FILE__ << ":" << __LINE__ << ": " << msg
#else
#define M_DebugLog( msg )
#endif

Methods must always be complete, compilable code; macros may be code fragments. Thus you can define a foreach macro:

#define foreach(list, index) for(index = 0; index < list.size(); index++)

And use it as thus:

foreach(cookies, i)
    printf("Cookie: %s", cookies[i]);

Since C++11, this is superseded by the range-based for loop.


Header file guards necessitate macros.

Are there any other areas that necessitate macros? Not many (if any).

Are there any other situations that benefit from macros? YES!!!

One place I use macros is with very repetitive code. For example, when wrapping C++ code to be used with other interfaces (.NET, COM, Python, etc...), I need to catch different types of exceptions. Here's how I do that:

#define HANDLE_EXCEPTIONS \
catch (::mylib::exception& e) { \
    throw gcnew MyDotNetLib::Exception(e); \
} \
catch (::std::exception& e) { \
    throw gcnew MyDotNetLib::Exception(e, __LINE__, __FILE__); \
} \
catch (...) { \
    throw gcnew MyDotNetLib::UnknownException(__LINE__, __FILE__); \
}

I have to put these catches in every wrapper function. Rather than type out the full catch blocks each time, I just type:

void Foo()
{
    try {
        ::mylib::Foo()
    }
    HANDLE_EXCEPTIONS
}

This also makes maintenance easier. If I ever have to add a new exception type, there's only one place I need to add it.

There are other useful examples too: many of which include the __FILE__ and __LINE__ preprocessor macros.

Anyway, macros are very useful when used correctly. Macros are not evil -- their misuse is evil.