Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

macro producing wrong number

Tags:

c

macros

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.

like image 642
Farzad Avatar asked Nov 11 '15 17:11

Farzad


2 Answers

You forgot the outer parenthesis, try this:

#define ABS(x) (((x) < 0) ? -(x) : (x))
like image 117
terence hill Avatar answered Oct 16 '22 14:10

terence hill


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

like image 35
Eugene Sh. Avatar answered Oct 16 '22 15:10

Eugene Sh.