|
-
September 21st, 2008, 03:47 AM
#5
Re: postfix
 Originally Posted by pooya
Compiler reads from right to left.
Your assumption is wrong. In fact in C++ the order of evaluation of subexpressions within an expression is unspecified (except for a few operators that enforce a specific order).
 Originally Posted by pooya
So first the a++ on the right gets processed. Since its postfix, operator + gets 0. and then a is set to 1. Now the a++ on the left gets processed. a=1 is passed to +, and then a is incremented by 1 to 2. So the final result should be 1.
Because the order is unspecified any postfix subexpression may be evaluated first but it doesn't matter which because the example is symmetric.
You have
a = 0;
b = a++ + a++;
When one of a++ is evaluated it's evaluated to 0. Because a is 0 when the other a++ is evaluated a stays 0. The two a++ evaluations have resulted in a being 0 so when then a+a is evaluated it becomes 0+0 = 0, which is assigned to b.
Say you have this instead,
a = 0;
b = ++a + ++a;
When one of ++a is evaluated it becomes 1. Because a is 1 when the other ++a is evaluated a becomes 2. The two ++a evaluations have resulted in a being 2 so when then a+a is evaluated it becomes 2+2 = 4, which is assigned to b.
The above may seem strange but that's what the MS compiler does. I'm sure other compilers could come up with other results. The reason for this is that the evaluation order is unspecified. The MS compiler's strategy seems to be to first perform all increments on a and then use the resulting a value in the sum, something it's entitled to do according to C++.
Last edited by _uj; September 21st, 2008 at 04:16 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|