#include<stdio.h>
#define f(x) (x<10) ? 1 : 3
int main(){
int i = f(1) + f(11);
printf("%d", i);
return 0;
}
Why in this case, the program output "1" but not "4".
How exactly do these two different uses of the defined macro work?
Look at what the compiler sees when pre-processing is done,
with some ()
added for clarity:
#include<stdio.h>
int main(){
int i = (1<10) ? 1 : (3 + (11<10) ? 1 : 3);
printf("%d", i);
return 0;
}
The reason for the ()
where I added them can be read here:
https://en.cppreference.com/w/c/language/operator_precedence
It shows that ?:
has low priority and the +
is pushing in to influence the result being evaluated for the first :
part.
Now it should be clear.
The solution is to generously use ()
within macro definitions.
Comments and other answers have already provided that, I repeat for completeness:
#define f(x) (((x)<10) ? 1 : 3)
I seem to have even more ()
than other proposals.
Mine also protects against funny things like f(12||12)
or f(0&&0)
behaving weirdly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With