0

This is just a quick question about when calculations are performed in a line of C++. Say I have the following block:

int numItems = 0;
inventory[numItems++] = "sword";
inventory[numItems++] = "armor";
inventory[numItems++] = "shield";

the ++ operator increments the array number of inventory AFTER it reaches the ; operator? All POST operations are performed at the end of a statement, and all PRE operations are performed at the beginning of a statement. Is that correct?

Just trying to make sure I have my head around how the code looks at things.

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by crapgarden
2

All POST operations are performed at the end of a statement, and all PRE operations are performed at the beginning of a statement. Is that correct?

It's close enough, yes. To be strictly precise, the update can happen any time between the previous and next sequence point as long as the result of the expression is correct. So in your code, it could potentially work like this:

int numItems = 0;
int temp;

temp = numItems;
++numItems;
inventory[temp] = "sword";

temp = numItems;
++numItems;
inventory[temp] = "armor";

temp = numItems;
++numItems;
inventory[temp] = "shield";
0

Thanks!
When you say 'result of the expression is correct' you mean the formatting/syntax of the calculation, or the actual value of the calculation?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.