#include <stdio.h>
#define abs(x) x > 0 ? x : -x
int main(void) {
printf("%d\n", abs(abs(3 - 5)));
return 0;
}
Why does the program above output 8 and not 2 while the program below outputs 2?
#include <stdio.h>
int abs(int x) {
return x > 0 ? x : -x;
}
int main(void) {
printf("%d\n", abs(abs(3 - 5)));
return 0;
}
Short answer is "because a macro is not a function".
Long answer is that macro parameters are expanded into the text of the program, so C compiler sees this long expression:
3 - 5 > 0 ? 3 - 5 : -3 - 5 > 0 ? 3 - 5 > 0 ? 3 - 5 : -3 - 5 : -3 - 5 > 0 ? 3 - 5 : -3 - 5
In the expansion, negative sign applies to 3
, not to (3-5)
, yielding negative 8.
Although you can work around this issue by placing parentheses around x
in the macro definition, defining an inline function would be a better choice.