[英]Assignment expression in C++ for-loop update expression
According to cppreference.com the update expression , or iteration expression , of a for cycle in C++ language can be根据cppreference.com , C++语言中for循环的更新表达式或迭代表达式可以是
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:因此,我认为以下 for cycle 是正确的:
//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?因此,在for循环的更新表达式中使用赋值表达式是否无效?
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.
请注意,逗号运算符从左到右计算,其中最左边的操作数保证首先执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.