Search code examples
coperatorspostfix-operator

confusion while subtracting and post decrementing at once


I'm stuck in a question of decrement the code is as follows

#include <stdio.h>
int main()
{
int x = 4, y = 3, z;
z = x-- - y;
printf("%d %d %d\n",x,y,z);

return 0;
}

according to what i know the output should be 4 3 0 the explanation for the value of z according to me is as follows: first as it's a post decrement so first we'll decrease the value of y from x i.e. 4-3 that's equal to 1 and according to me we'll again decrease 1 from this 1 (or we don't correct me if I'm wrong here) and the output will be 0.


Solution

  • The expression x-- evaluates to the current value of x which is 4. The value of y is then subtracted from this value resulting in 1 which is what is assigned to z. x is then decremented as a side effect of the postdecrement.

    So the output will be 3 3 1.