C macros versus inline functions
A #define macro is text substitution done by the preprocessor before compilation. The macro's argument is pasted wherever the parameter appears, so an argument with a side effect, such as i++ or a function call, can run more than once. That is a classic source of bugs.
C
#include <stdio.h>
#define MAX_MACRO(a, b) ((a) > (b) ? (a) : (b))
static inline int max_function(int a, int b) {
return a > b ? a : b;
}
static int calls = 0;
static int five(void) {
calls++;
return 5;
}
int main(void) {
int i = 3;
int from_macro = MAX_MACRO(i++, 2);
printf("macro: result %d, i = %d\n", from_macro, i);
int j = 3;
int from_function = max_function(j++, 2);
printf("function: result %d, j = %d\n", from_function, j);
calls = 0;
int m = MAX_MACRO(five(), 2);
printf("macro called five() %d times (result %d)\n", calls, m);
calls = 0;
int f = max_function(five(), 2);
printf("function called five() %d time (result %d)\n", calls, f);
return 0;
}