In what order does evaluation of post-increment operator happen?

隐身守侯 提交于 2019-12-01 20:57:18

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.

When in doubt, prefer the form which is easier to understand (expand the loop).

(And I think list[i] = objects.at(i++) leads to undefined behavior.)

Referencing i in the same expression as i++ is probably undefined behavior. But since it looks like you're using containers, could you maybe write...

list = objects;                               // if they're the same type
list.assign(objects.begin(), objects.end());  // if not

As it has been said already, post-incrementing a variable in the same expression it is used yields undefined behaviour. However, if you wish to keep the compact form, you could introduce a sequence point and go for

for(unsigned int i = 0; i < objects.size(); list[i] = objects.at(i), i++);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!