C++ Post-Increment Operator – Evaluation Order Explained

c++operator-precedencestl

Given

std::vector<CMyClass> objects;
CMyClass list[MAX_OBJECT_COUNT];

Is it wise to do this?

for(unsigned int i = 0; i < objects.size(); list[i] = objects.at(i++));

Or should I expand my loop to this?

for(unsigned int i = 0; i < objects.size(); i++)
{
  list[i] = objects.at(i);
}

Best Answer

The former is undefined behavior. It's not specified whether list[i] is evaluated (to provide an lvalue for the lhs of the assignment) before or after the function call to objects.at.

Hence there is a legal ordering of the various parts of the expression, in which i is accessed (in list[i]) and separately modified (in i++), without an intervening sequence point.

This is precisely the condition for undefined behavior in the C++ standard - whether such a legal ordering exists. IIRC the C standard expresses it slightly differently but with the same effect.

If in doubt, don't write an expression which uses an increment operator, and also uses the same value anywhere else in the expression. You can do it with the comma operator (i++, i++ is fine) and the conditional operator (i ? i++ : i-- is fine) because they have sequence points in them, but it's rarely worth it. || and && likewise, and something like p != end_p && *(p++) = something; isn't totally implausible. Any other use, and if you stare at it long enough you can usually work out an order of evaluation that messes things up.

That's aside from the comprehensibility of complicated for expressions and for loops with empty bodies.

Related Question