embedded software boot camp

Coding Standard Rule #9: Don’t Create Function-Like Macros

Friday, April 3rd, 2009 by Michael Barr

Rule: Parameterized macros shall not be used if an inline function can be written to accomplish the same task.

Example:

#define MAX(A, B)   ((A) > (B) ? (A) : (B))     // Don’t do this ...inline int max(int a, int b)           // ... if you can do this instead.

Reasoning: There are a lot of risks associated with the use of preprocessor #defines, and many of them relate to the creation of parameterized macros. The extensive use of parentheses (as shown in the example) is important, but does not eliminate the unintended double increment possibility of a call such as MAX(i++, j++). Other risks of macro misuse include comparison of signed and unsigned data or any test of floating-point data. The C++ keyword inline was added to the C standard in the 1999 ISO update.

Coding Standard Rule #8
Coding Standard Rule #10

These rules are excerpts from the Embedded C Coding Standard book.

Tags: , , ,

3 Responses to “Coding Standard Rule #9: Don’t Create Function-Like Macros”

  1. Bryce Schober says:

    What about static and constant initializations that need to respond to various configurations at compile time? I would rather have function-style macros for that purpose than magic numbers. In fact, you can make function-style macros *almost* as safe as inline functions, but it does take a heck of a lot more work. And once you have (using local variables, manual type-checking, etc.), you won’t be able to use it for static and constant initialization anymore.

  2. Michael Barr says:

    More info from Bryce (via e-mail exchange):A simple example would be conversions to a non-human-readable format at compile time, like:const int pitch_limit = DEG_2_BINCIRC( 10 );I don’t think any compiler will let you use an inline function for that, which is why I have inline functions *and* function-style macros for things like fixed-point conversions and such. I suppose this is just one of those circumstances in which an inline function can’t accomplish the same task, but it’s a pretty significant one to me.

  3. ananth says:

    Hi Bryce,A newbie question. Why would a compiler not allow inline functions for the example that you have cited? Explanation with some more detail would really help clarify the point further.Ananth

Leave a Reply