According to cppreference.com the update expression , or iteration expression , of a for cycle in C++ language can be
any expression, which is executed after every iteration of the loop and before re-evaluating condition.
Hence, I thought that the following for cycle was correct:
//initializations
Point cursor;
cursor.y = minR * pixelSpacing.y + origin.y;
for (int r = minR; r <= maxR; r++, cursor.y += pixelSpacing.y, cursor.x = minC * pixelSpacing.x + origin.x)
{
//loop statements
}
However, the results I obtain at the end of the cycle are different from the ones obtained with the following code:
//initializations
Point cursor;
cursor.y = minR * pixelSpacing.y + origin.y;
for (int r = minR; r <= maxR; r++, cursor.y += pixelSpacing.y)
{
cursor.x = minC * pixelSpacing.x + origin.x;
//loop statements
}
Is it therefore not valid to use an assignment expression in an update expression of a for loop?
This
for (int r=minR; r<=maxR; r++, cursor.y += pixelSpacing.y, cursor.x = minC * pixelSpacing.x + origin.x)
is equivalent to this:
for (int r=minR; r<=maxR; /* nothing here */)
{
/* loop body here */
r++;
cursor.y += pixelSpacing.y;
cursor.x = minC * pixelSpacing.x + origin.x;
}
So the only difference is the order in which you execute the various statements. Note that the comma operator evaluates left-to-right, where the left-most operand is guaranteed to be executed first.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.