What is the value of "val" after for's first loop?
for (int val = 1; val <= 10; ++val)
cout << val <<endl; //I expected 2, but the result was 1.
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."
Please give me the specific answer. Thanks!
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;
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.
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.
Originally Posted by DaWei