Why is this an issue?
It is tempting to treat function-like macros as functions, but the two things work differently. For instance, the use of functions offers parameter
type-checking, while the use of macros does not. Additionally, with macros, there is the potential for a macro to be evaluated multiple times. In
general, functions offer a safer, more robust mechanism than function-like macros, and that safety usually outweighs the speed advantages offered by
macros. Therefore functions should be used instead when possible.
Noncompliant code example
#define CUBE (X) ((X) * (X) * (X)) // Noncompliant
void func(void) {
int i = 2;
int a = CUBE(++i); // Noncompliant. Expands to: int a = ((++i) * (++i) * (++i))
// ...
}
Compliant solution
inline int cube(int i) {
return i * i * i;
}
void func(void) {
int i = 2;
int a = cube(++i); // yields 27
// ...
}
Resources
- MISRA C:2004, 19.7 - A function should be used in preference to a function-like macro.
- MISRA C++:2008, 16-0-4 - Function-like macros shall not be defined.
- MISRA C:2012, Dir. 4.9 - A function should be used in preference to a function-like macro where they are interchangeable
- CERT, PRE00-C. - Prefer inline or static functions to function-like macros
- C++ Core
Guidelines ES.31 - Don’t use macros for constants or "functions"