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
// ...
}