-1

For this code

int j=2;
int c=(j++)*(j++);
printf("%d\n",c);

I get the value of c as 6

While for below code

int j=2;
int c=(++j)*(++j);
printf("%d\n",c);

I get the value of c as 16

Can someone please explain this case to me ?

zk9099
  • 183
  • 10
  • The code invokes undefined behaviour. There is no correct answer. Compilers can do what they like; what they like is correct; you have no cause for complaint. Different compilers will handle the same code differently. They're all 'correct'. – Jonathan Leffler Jan 22 '17 at 07:20

1 Answers1

1

You are simultaneously modifying the value of a variable, and using that variable in an expression. As such, your code is exhibiting undefined behavior. Undefined behavior is exactly that; anything can happen. There is no logical way to predict what values will result from the code you have written.

verbose
  • 7,827
  • 1
  • 25
  • 40