I can't understand why the following code prints 2 instead of 1...
#include <stdio.h>
#define ABS(x) ((x) < 0) ? -(x) : (x)
int main()
{
printf("%d", ABS(ABS(-2)-(ABS(-3))));
return 0;
}
This question was on our exam and I answered the output is 1 but after compiling I get 2... Would anyone please explain what the expression actually do... Thanks in advance.
You forgot the outer parenthesis, try this:
#define ABS(x) (((x) < 0) ? -(x) : (x))
There is a problem with parentheses. If you expand the macro, you will get a complex nested ternary operations, which evaluate to 2
(See the expansion in the update). In order to get a desirable result surround the macro with parenthesis.
Update: The manual expansion:
ABS(ABS(-2)-(ABS(-3)))
expands to:
((ABS(-2)-(ABS(-3))) < 0) ? -(ABS(-2)-(ABS(-3))) : (ABS(-2)-(ABS(-3)))
ABS(-3)
is surrounded by parentheses everywhere, so it is safely evaluated to 3
, so no need to expand it. So we end up:
(( ((-2) < 0) ? -(-2) : (-2) - 3) < 0) ? -(ABS(-2)-3) : (ABS(-2)-3)
(ABS(-2)-3)
will expand to
((-2) < 0) ? -(-2) : (-2) - 3 = 2
Evaluating the whole:
(( true ? 2 : -5 < 0) ? -2 : 2
or
(2 < 0) ? -2 : 2 = 2
And it is the observed result, hope it is followable.
which is eno
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