Reputation: 7005
The following two lines of code are not returning the same value. Any reason for that?
int i;
i = 1;
i = i + i++; //Returns 2, expecting 3
And
i = 1;
i = i++ + i; //Returns 3
Semantically, this should be the same a + b = b + a
right?
The same with decreasing i
:
i = 1;
i = i - i--; //Returns 0, expecting 1
And
i = 1;
i = i-- - i; //Returns 1, expecting -1
What confuses me even more is the usage of post increment operators:
i = 1;
i = i + ++i; //Returns 3
And
i = 1;
i = ++i + i; //Returns 4, expecting 3
Same again with decreasing operator:
i = 1;
i = i - --i; //Returns 1
And
i = 1;
i = --i - i; //Returns 0, expecting -1
Last Question:
How are these two lines interpreted by the compiler?
i = i+++i; // is it i + ++i or i++ + i?
i = i---i; // is it i - --i or i-- - i?
Upvotes: 1
Views: 3369
Reputation: 1150
Precedence of increament or decreament operator is always higher than arithmetic operators like + - * /
Refer http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx for details.
Also the value of postfixed increament or decreament operator is effective only after the current statement.
For eg:
i = i + i++ = 1 + 1++ = 1 + 1 = 2; // value of i is effective after increament is done
i = i++ + i = 1++ + 2 = 3; //Next value of i contains updated value i.e. 2
i = i + ++i = 1 + ++1 = 1 + 2 = 3; //Next value of i contains updated value i.e. 2
i = ++i + i = ++1 + i = 2 + 2; //Both value of i contains updated value i.e. 2 because of prefixed operator
i = i+++i = i++ + i;
i = i---i = i-- - i;
Upvotes: 0
Reputation: 200
I think the best way to try to understand this, is look at what the compiler makes of this.
See here for an overview of this for the case
x=i-- - --i;
https://stackoverflow.com/a/8573429/959028
best regards
Upvotes: 0
Reputation: 32661
i = i + i++; //Returns 2, expecting 3
Know as post increment. Value will be used first and then incremented. It is equivalent to
i = i + i;
i = i+1;
and this is pre-increment. Value will be incremented first and then used.
i = i++ + i; //Returns 3
is equivalent to
i = i+1;
i = i + i;
i = i+++i; // is it i + ++i or i++ + i?
is interpretted as
i = i + 1; i = i + i;
and this
i = i---i; // is it i - --i or i-- - i?
is interpretted as
i= i-1;
i = i-i;
Upvotes: 3
Reputation: 65049
There is a difference between pre-increment (++i
) and post-increment (i++
). The difference is:
Pre-increment will add the value before using the result. Post-increment will use the reslt.. then add the value. So, your first example:
int i;
i = 1;
i = i + i++; // First use equals 1, second use equals one. After this line though
// i equals 2, because of your use of post-increment.
Likewise, your second example:
i = 1;
i = i++ + i; // First use is 1. After the first use.. it is incremented..
// The second use it is 2. Therefore, 1 + 2 == 3.
As for your last question... why not put it into a console application and try it yourself?
Upvotes: 2