In C++ the expression on the right hand side (RHS) of the =
sign is evaluated first, because you can't store (assign) a value in a variable if you haven't calculated what it is!
int myAge = 10 + 10; // calculates 20 first, then stores it.
You're changing the value of n before assigning to position n in your array - increasing it from 0 to 1 in the first iteration of the loop - and so assigning the result, 1, to array[1].
Why? Well, ++n
and n++
are complicated (and frequently confusing) operators in c++, in that that they're both mathematical and assignment operators. ++n is essentially equivalent to:
n = n + 1;
return n;
Where n++ is closer to:
n = n+1;
return n -1;
You can code it more explicitly with simpler operators:
arr[n] = n+1;
n = n+1;
.. or use a for loop as you did in your output code. Using the same looping structures for both might help you achieve consistent outcomes.
You're not alone in struggling with this one. Chris Lattner felt the ++
and --
unary operators' potential for obfuscation and bugs sufficiently outweighed their benefits that they were dropped from Swift 3.