-2
#include <stdio.h>
#define test(x) x*x
#define test2(x) x
int main(void) {    
int x=5;
printf("%d %d %d %d %d %d",test2(x), test2(x-2), test(x), test(x-2),4*(test(x-3)),4*test(x-3));
return 0;
}

This gives the output as :

5 3 25 -7 -52 2

Well can understand for first 3 but why -7 when test(x-2) and for last 2…

GodFather
  • 13
  • 3

2 Answers2

3

After compiler preprocessing step your printf becomes

printf("%d %d %d %d %d %d",x, x-2, x*x, x-2*x-2,4*(x-3*x-3),4*x-3*x-3);

x-2*x-2 is evaluated as: x-2*x-2 -> x-(2*x)-2

5-10-2

= -7

ie * takes precedence over -

Pras
  • 4,047
  • 10
  • 20
  • Mention *preprocessor* and distinguish that from the ensuing C-compilation and this answer will be a considerably more complete. A suggestion about surrounding the expression usages with parens and how it changes the behavior would also be stellar. – WhozCraig May 11 '17 at 04:01
1

Your this expression will expand something like given at the second code snippet: Below code is indented just to easily show you the code, I know it is syntactically wrong. :)

printf("%d %d %d %d %d %d",test2(x), 
                           test2(x-2), 
                           test(x), 
                           test(x-2),
                           4*(test(x-3)),
                           4*test(x-3));

After expansion:

printf("%d %d %d %d %d %d",x, 
                           x-2, 
                           x*x, 
                           x-2*x-2,
                           4*(x-3*x-3),
                           4*x-3*x-3);

Macros doesn't replace expression with brackets enabled, rather it does the literal replacement.

If you do the maths, you will get the answer which you had already shown on the top.

surajs1n
  • 1,493
  • 6
  • 23
  • 34