Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Postfix and prefix operator: why the value comes out as the same? (http://www.go4expert.com/forums/postfix-prefix-operator-value-t6834/)

hbchen 15Oct2007 06:56

Postfix and prefix operator: why the value comes out as the same?
 
What is the value of "val" after for's first loop?
A.
for (int val = 1; val <= 10; ++val)
{
cout << val <<endl; //I expected 2, but the result was 1.
}
B.
for (int val = 1; val <= 10; val++)//Result: 1
{
cout << val <<endl; //I expected 1, the result was 1.
}
Why got the same value?
I looked at the explanation, but do not quite understand why the results came that way:
" The postix increment operation occurs after the operand is evaluated.
In the prefix form, the increment takes place before the value is used in expression evaluation, so the value of the expression is different from the value of the operand.
See section 1.9.17 in the C++ standard for more information."
source: http://msdn2.microsoft.com/en-us/library/dy3d35h8(VS.80).aspx

Please give me the specific answer. Thanks!

DaWei 15Oct2007 07:09

Re: Postfix and prefix operator: why the value comes out as the same?
 
In this situation, pre- or post-increment doesn't matter. val isn't evaluated until after the incrementing statement. The breakdown of your loop looks like this:

val = 1;
LOOP:
if (val > 10) EXIT FROM LOOP
cout << val << endl; First time through, val is 1.
val++; OR ++val;
// val is now 2, either way. There is no evaluation taking place at this step.
GOTO LOOP
LOOPEXIT

You would need to know which to use if you were evaluating val in that same sequence point. For instance,

val = 1;
if (val++ == 1) // this is true because the comparison is made BEFORE the increment.

val = 1
if (++val == 1) // this is false because the increment is made BEFORE the comparison.

hbchen 15Oct2007 08:49

Re: Postfix and prefix operator: why the value comes out as the same?
 
Quote:

Originally Posted by DaWei
In this situation, pre- or post-increment doesn't matter. val isn't evaluated until after the incrementing statement. The breakdown of your loop looks like this:
...

Thank you, DaWei! You've made it exceptionally clear!


All times are GMT +5.5. The time now is 19:53.