Postfix and Prefix

Hey guys I am having a problem with getting this program :
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main(){
int z,x=5,y=-10,b=2,a=4;
z=x++ - --y*b/a;
cout<<z;
return 0;
}


Why is the output = 10 ?
Let's turn the question around. Why do you think it shouldn't be 10?
1
2
3
4
5
6
7
z=x++ - --y*b/a;
z=5++ - --(-10)*2/4;
z=5 - -11*2/4; // the ++ is lost because it'll take effect on x AFTER the instruction
z=5 - -22/4;
z=5 - -5; // we have integer division, we lose the rational part of 5.5 (which is 0.5)
z=5 + 5;
z=10;
Aha , but why didn't we do the same with --y in line 3 ? I mean we didn't add 1 to x but we did to y ...
Thats because ++ or -- used as a prefix are computed instantly and ++ or -- used as a postfix are computed after the instruction, just like catfish has written
Topic archived. No new replies allowed.