In what order is the post-increment statement evaluated?

Considering

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

Can this be done?

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

Or do I need to expand my cycle to this?

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

The first is undefined behavior. He did not indicate whether list[i](to provide an lvalue for the lhs assignment) is evaluated before or after the function is called on objects.at.

Therefore, there is legal ordering of the various parts of the expression in which iaccess is made (in list[i]) and separately changed (in i++) without an intermediate point in the sequence.

undefined ++ - . IIRC C , .

, , increment, . (i++, i++ is fine), (i ? i++ : i-- ), , . || && , - p != end_p && *(p++) = something; . , , , .

for for .

+11

, , ( ).

( , list[i] = objects.at(i++) undefined.)

+6

i , i++, , undefined. , , ...

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

As already mentioned, post-incrementing a variable in the same expression that is used gives undefined behavior. However, if you want to keep a compact shape, you can enter a sequence point and go to

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

Source: https://habr.com/ru/post/1738976/


All Articles