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 used in preference to 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-A. Use parentheses within macros around parameter names, and PRE02-A. 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 appears, and not where the function is called; and identifiers refer to the declarations in scope where the body occurs.
...
Code Block |
---|
#define ADD_M(a, b) ((a) + (b)) static inline add_f(int a, int b) { return a + b; } |
In this example, the ADD_M(3,4)
macro invocation yields a constant expression, while the add_f(3,4)
function invocation does not.
...