Macros are dangerous because their use resembles that of real functions, but they have different semantics. C99 adds inline functions to the C programming language. 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. , "Never invoke an unsafe macro with arguments containing assignment, increment, decrement, volatile access, or function call," PRE01-C. , "Use parentheses within macros around parameter names," and PRE02-C. , "Macro replacement lists should be parenthesized.")
Inline substitution is not textual substitution, nor does it create a new function. For example, the expansion of a macro used within the body of the function uses the definition it had at the point the function body appeared, and not where the function is called; and identifiers refer to the declarations in scope where the body occurs.
...
which is undefined (see EXP30-C. , "Do not depend on order of evaluation between sequence points").
Compliant Solution
When the macro definition is replaced by an inline function, the side effect is executed only once before the function is called.
...
Wiki Markup |
---|
In this noncompliant code example, the programmer has written a macro called {{EXEC_BUMP()}} to call a specified function and increment a global counter \[[Dewhurst 02|AA. C References#Dewhurst 02]\]. When the expansion of a macro is used within the body of a function, as in this example, identifiers refer to the declarations in scope where the body occurs. As a result, when the macro is called in the {{aFunc()}} function, it inadvertently increments a local counter with the same name as the global variable. Note that this example violates [DCL01-C., "Do not reuse variable names in subscopes]." |
Code Block | ||
---|---|---|
| ||
size_t count = 0; #define EXEC_BUMP(func) (func(), ++count) void g(void) { printf("Called g, count = %zu.\n", count); } void aFunc(void) { size_t count = 0; while (count++ < 10) { EXEC_BUMP(g); } } |
...
This noncompliant code example also violates EXP30-C. , "Do not depend on order of evaluation between sequence points."
Compliant Solution
The execution of functions, including inline functions, cannot be interleaved, so problematic orderings are not possible.
...
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."
Type-generic macros may also be used, for example, to swap two variables of any type, provided they are of the same type.
...