1
#include <stdio.h>
#define func(x, y) x + y/x
int main() {
    int i = -1, j = 2, x;
    printf("i = %d\n", i);
    printf("j = %d\n", j);
    printf("x = %d\n", x);
    x = func(i + j, 3);
    printf("%d\n",x);
    return 0;
}

In the C code above, the output is 0 while I expect 4. i.e.

i + j = -1 + 2 = 1   
func(i+j, 3) = func (1,3) = 1 + 3/1 = 1 + 3 = 4.   

Where am I wrong? Where will I get to learn more about C-pre-processor macro behavior?

The output of the above code is as below:

Output Console

Community
  • 1
  • 1

1 Answers1

3

change

#define func(x, y) x + y/x

To

#define func(x, y) ((x) + (y)/(x))

Reason :

func(x, y) x + y/x  
x = i + j
y = 3
func(x, y) = func(i + j, 3)
=  x + y/x
=  i + j + 3/i + j
= -1 + 2 + 3/(-1) + 2
=  1 - 3 + 2
=  0
skr
  • 2,146
  • 19
  • 22