[try Beta version]
Not logged in

 
Initializing Arrays with Increment Operators

Nov 10, 2013 at 3:40pm
I'm currently taking my first C++ class, and the book has an example of declaring array values with an increment operator. When I first saw the code I thought that it was skipping position 0 of the array because of the increment, but when I run the code I can see that it's not. I am trying to understand why that's so.

The code I am referring to is below.

1
2
3
4
  int numItems=0;
	inventory[numItems++] = "rusty short sword";
	inventory[numItems++] = "armor";
	inventory[numItems++] = "shield";


When I see that code I think: OK this is going to assign "rusty short sword" to inventory[1], because numItems is 0, and this array initialization increments numItems so it's actually going to be set to position 1 in the array, not 0.

However that doesn't seem to be the case, and I don't quite understand why. I can't find anything that explains this in more detail either. Can someone help shed some light on this?
Last edited on Nov 10, 2013 at 3:41pm
Nov 10, 2013 at 3:47pm
The postfix increment is handled after the array subscript.

Equivalent code:
1
2
3
4
...
inventory[numItems] = "rusty short sword";
numItems++;
...


The prefix increment will behave the way you describe:
1
2
3
...
inventory[++numItems] = "rusty short sword";
...


Operator precedence: http://en.cppreference.com/w/cpp/language/operator_precedence
Nov 10, 2013 at 4:01pm
Thank you for clarifying that - makes much more sense now. Seeing the equivalent code helps a lot.
Topic archived. No new replies allowed.