0

I have a question about macros in c, Here is my code!

#include <stdio.h>
#define product(x) (x*x)

int main(){
    int i=3,j;
    j = product(i+1);
    printf("%d",j);
}

i guessed the answer as 16 but answer is 7, How is it possible?

#include <stdio.h>
#define product(x) (x*x*x)

int main(){
    int i=3,j;
    j = product(i+1);
    printf("%d",j);
}

answer of this is 10

  • 1
    Because it expands to `product((i+1*i+1));` which (because `*` has higher precedence than `+`) is `product(i+(1*i)+1);` Use parentheses around `x` in the macro: `#define product(x) ((x)*(x))`. – 001 Nov 17 '22 at 15:02
  • Macro arguments are not evaluated; a macro is simply a text (token) substitution. The preprocessor will replace (expand) the source text `product(i+1)` with the text `(i+1*i+1)` before compiling. Hence why you're being bitten by precedence issues as Johnny says above. – John Bode Nov 17 '22 at 15:15

0 Answers0