-3

First of all, I would like to apologize, if this question has been asked before in this forum. I searched, but could't find any similar problem.

I am a beginner in C. I was going through a tutorial and came across a code, the solution of which I can't understand.

Here is the code -

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

int main()
{
    int i=3, j, k;

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

    return 1;
}

I tried running the code through compiler and got the solution as "j = 12" and "k = 49".

I know how #define works. It replace every occurrence of PRODUCT(x) by (x*x), but what I can't grasp is how j and k got the values 12 and 49, respectively.

Any help would be appreciated.

Thank you for your time.

Ashish
  • 29
  • 5

1 Answers1

4

Your code will invoke undefined behavior. Anything could happen. The macro in statements

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

will be expanded to

j = x++ * x++;
k = ++x * ++x;  

In both statements x is being modified more than once between two sequence points.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 1
    ...and that goes into my 'Rep-PersonalServicesWorker of the Month' bookmanrks. – Martin James Apr 15 '16 at 20:01
  • @MartinJames; Well I already got your comment on the question. No need to repeat here. I am not taking it offensive anyway. Different people different shades. – haccks Apr 15 '16 at 20:05