The Macro Mistake
10/14/2012
When writing C code, when is it beneficial to use a macro when a function call would work? In the 1978 book THE C PROGRAMMING LANGUAGE, the authors of the language give two examples. The first example is the max macro and its ability to operate on different data types. This single macro definition can be invoked to compare a pair of integers or a pair of doubles or a pair of pointers. The second example is the getchar macro. For this example, the authors list avoiding the overhead of a function call as valuable.
Today, the justification in first example is still true. If a single C function is needed that can operate on dissimilar data types without implicit type casting, then use of a macro may be appropriate. However, the justification is the second example is no longer true. After 35 years of compiler and processor improvement, any benefit from using a macro to force inlining of code has been eliminated. A compiler will inline the code for small functions when optimizing for speed. When optimization is disabled for a debug build, the function will be called. This has the advantage of allowing a source level debugger to easily find the source code for the function, something not possible with a macro.
Though software development tools have evolved and improved over the past 35 years, C code projects have become larger and more complex. Today, it can be difficult to find the code for a macro call when several macros with the same name exist in the project. On the other hand, the code for a function call is easy to find, even if several functions with the same name exist in the project. With a non-optimized build and a source level debugger, stepping into the function call will reliably locate the proper source code.
Why do C programmers still use macros in situations where a function call is superior in every aspect?