I've been trying to make sense of the functionalities of ++x and x++, but the minute I feel like I've figured it out, something new comes up that doesn't make sense with the previous rules.
So as far as I know, when using (++x),first the value of x increases by 1, and then the value of new (x) is assigned to the parenthesis (++x). On the other hand when using (x++), first the value of (x) is assigned to the parenthesis (x++), and then the value of x itself increases by 1.
For example I expect the output of this code:
int c=9;
int x=(++c)-c;
cout<<"c="<<c<<endl<<"x="<<x;
To be c=10 x=0
, and so it is.
Or also this code:
int c=9;
int x=(c++)-(++c);
cout<<"c="<<c<<endl<<"x="<<x;
with output of c=11 x=-2
, which also makes sense and is totally expected.
What doesn't make sense is that the output of this code:
int c=9;
int x=(++c)-(c++);
cout<<"c="<<c<<endl<<"x="<<x;
is c=11 x=1
, which I expected it to be c=11 x=0
. Because from left to right, first the value of c is increased by 1 (which means c=10), and then (++c) is replaced with the new value of c (which is 10). Moving on to the next parenthesis, first (c++) is replaced with the value of c (which is 10), and then the value of c itself is increased by 1, which means at the end we have c=11 and x=10-10=0.
The same issue with this code:
int c=9;
int x=(++c)*(c++);
cout<<"c="<<c<<endl<<"x="<<x;
generating this output c=11 x=110
, which also doesn't make sense (I expected it to be c=11 x=100
, with the exact same logic for the previous code)
And also this last one in which I have no idea what is going on:
int c=1;
int x=(++c)*(++c)*(++c);
cout<<"c="<<c<<endl<<"x="<<x;
with output of c=4 x=36
(which I expected to be c=4 x=24
)!
The funnier part is that if I change the second line to int x=2*(++c)*(++c)*(++c);
, the output changes to c=4 x=48
!
I'd be grateful if anyone could help me with this.