Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Macros are dangerous because their use resembles that of real functions, but they have different semantics. The inline function-specifier was introduced to the C programming language in the C99 standard. Inline functions should be preferred over macros when they can be used interchangeably. Making a function an inline function suggests that calls to the function be as fast as possible by using, for example, an alternative to the usual function call mechanism, such as inline substitution. (See also PRE31-C. Avoid Do not perform side effects in arguments to unsafe macros, PRE01-C. Use parentheses within macros around parameter names, and PRE02-C. Macro replacement lists should be parenthesized.)

...

which is undefined. (See EXP30-C. Do not depend on order of evaluation for side - effects.)

Compliant Solution

When the macro definition is replaced by an inline function, the side effect is executed only once before the function is called:

...

Unlike functions, the execution of macros can interleave. Consequently, two macros that are harmless in isolation can cause undefined behavior when combined in the same expression. In this example, F() and G() both increment the global variable operations, which causes problems when the two macros are used together:

...

This noncompliant code example also violates EXP30-C. Do not depend on order of evaluation for side - effects.

Compliant Solution

...

PRE00-EX4: Macros can be used to implement type-generic functions that cannot be implemented in the C language without the aid of a mechanism such as C++ templates.

An example of the use of function-like macros to create type-generic functions is shown in MEM02-C. Immediately cast the result of a memory allocation function call into a pointer to the allocated type.

...