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!
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.