Arithmetic

How come the answer is 0 3 2?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
int x = 3;
int y = 2;
int z = 1;
x -= 5 - y;
y *= 2 + x - z;
z = y++;
cout << x << " " << y << " " <<z;

return 0;
}
Its to do with the order of precedence of operators. For example

x -= 5 - y;

This is executed as x -= (5 - y); // 5 - y = 3, therefore x -= 3 is equal to 0

It is not executed as (x -= 5) - y; // which would be (3-5) - 2 = -4
Pay attention to what is happening on each line. To help you get started, I'll do line 10:

10 x -= 5 - y;

which is the same as

10 x = x - (5 - y); 3 - (5 - 2)

10 x = x - (3); 3 - (3)

10 x = 0; 0

Now after line 10, x has the value 0.

Hope this helps.
Now I know that order of precedence is impt. Tks.
Topic archived. No new replies allowed.