-2

Can't understand why this output producing. Please explain with details.

The below code is giving me the desired output. Like

#include <stdio.h>
#define product(p,q) p*q
int main()
{
        printf("%d",product(5,3));

    return 0;
}

Output:

15

But the same logic and macro in the below code give me output like below.

#include <stdio.h>
#define product(p,q) p*q
int main()
{
    int x=3,y=4;
    printf("%d",product(x+2,y-1)); // x+2=5 and y-1=3

    return 0;
}

Output:

10
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

1

Your problem is, that the "*" operator has a higher operator precedence than "+".

Try unwrapping the macro:

 product(x+2,y-1)
=x+2*y-1
=x+2y-1
=x-1+2x

You have to add parentheses around every operator:

#define product(p,q) ((p)*(q))
JCWasmx86
  • 3,473
  • 2
  • 11
  • 29