Search code examples
cprefixpostfix-operator

operation of prefix and postfix operators in c


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 ?


Solution

  • 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.