1

My code:

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

int main()
{
    int i = 3, j, k, l;
    j = PRODUCT(i + 1);
    k = PRODUCT(i++);
    l = PRODUCT(++i);
    printf("%d %d %d %d", i, j, k, l);
    return 0;
}

I am not able to comprehend why the output is:

7 7 12 49. 

Is there any error in macro or some other problem?

anastaciu
  • 23,467
  • 7
  • 28
  • 53

2 Answers2

6

Your code has undefined behavior, operations in i:

k=PRODUCT(i++);
l=PRODUCT(++i);

lack a sequence point.

As for:

j=PRODUCT(i+1);

It expands to i+1*i+1 which is i+i+1 which is 7. I assume it's not the expected result, in the future also include that in your question.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
5

Your macro is incorrect. The following expression:

PRODUCT(i+1)

will expand to

(i+1 * i+1)

which is 2*i+1.

Your macro should be:

#define PRODUCT(x) ((x)*(x))

I strongly suggest you stop using macros for this sort of thing. You could easily write this as a function:

int product(int x)
{
  return x * x;
}

Note that this will only work for the example I gave. If you try

PRODUCT(i++)

you will get

( (i++) * (i++) )

which invokes undefined behaviour, as this expression lacks a sequence point between the 2 increments.

cigien
  • 57,834
  • 11
  • 73
  • 112