Preprocessor
Macro Pitfall
Missing parentheses in a macro can change expression precedence.
Macro Pitfall
macro_pitfall.c
#include <stdio.h>
#define BAD_TRIPLE(n) n * 3
#define GOOD_TRIPLE(n) ((n) * 3)
int main(void) {
int value = ;
int bad = value + 1 * 3;
int good = ((value + 1) * 3);
printf("bad=%d good=%d\n", bad, good);
return 0;
}
#include <stdio.h>
#define BAD_TRIPLE(n) n * 3
#define GOOD_TRIPLE(n) ((n) * 3)
int main(void) {
int value = ;
int bad = value + 1 * 3;
int good = ((value + 1) * 3);
printf("bad=%d good=%d\n", bad, good);
return 0;
}
#include <stdio.h>
#define BAD_TRIPLE(n) n * 3
#define GOOD_TRIPLE(n) ((n) * 3)
int main(void) {
int value = ;
int bad = value + 1 * 3;
int good = ((value + 1) * 3);
printf("bad=%d good=%d\n", bad, good);
return 0;
}
text substitution
A macro expands as text, so operator precedence still matters afterward.
safer macro
Wrap parameters and the full replacement expression in parentheses.
direct comparison
The replay compares the expanded bad and good expressions directly.