C++:for 循环中的多个退出条件(多个变量):AND -ed 或 OR -ed?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18063552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?
提问by user3728501
For loops and multiple variables and conditions.
For 循环和多个变量和条件。
I am using a for loop to set source and destination indexes to copy items in an array.
我正在使用 for 循环来设置源和目标索引以复制数组中的项目。
for(int src = 0, dst = 8;
src < 8, dst >= 0;
src ++, dst --)
{
arr2[dst] = arr1[src];
}
Something like that anyway.
反正就是这样。
(AND) || (||)
(AND) || (||)
My question is about the exit conditions. There are two here. src < 8
and dst >= 0
. Are these conditions AND-ed (&&
) or OR-ed (||
).
我的问题是关于退出条件。这里有两个。src < 8
和dst >= 0
。这些条件是 AND&&
运算( ) 还是 OR 运算 ( ||
)。
To further explain, are the conditions evaluated like this:
为了进一步解释,条件评估如下:
(src < 8) && (dst >= 0)
Or are they evaluated like this?
还是他们是这样评价的?
(src < 8) || (dst >= 0)
Or is it something else entirely different? I imagine the logical thing to do would be to evaluate one of the two ways I specified above, and not something else.
或者是其他完全不同的东西?我想合乎逻辑的做法是评估我上面指定的两种方式之一,而不是其他方式。
回答by Reed Copsey
The comma operator will return the value of the right expression, so writing this:
逗号运算符将返回正确表达式的值,因此编写如下:
src < 8, dst >= 0;
As a condition will be the same as just writing dst >= 0
. The src < 8
will be completely ignored in this case, as it's evaluated separately from the second condition, and then the second condition is returned. This doesn't evalute to AND or to OR, but in fact just has the effect of "throwing away" the first check entirely.
作为条件将与仅写入相同dst >= 0
。的src < 8
将在此情况下,可以完全忽略,因为它是从第二个条件分别进行评估,然后返回第二个条件。这不会计算 AND 或 OR,但实际上只是具有完全“扔掉”第一个检查的效果。
If you want to evaluate this correctly, you should use one of your two options (explicitly specifying the behavior via ||
or &&
).
如果您想正确评估这一点,您应该使用两个选项之一(通过||
或明确指定行为&&
)。
For details, see Comma Operator:
有关详细信息,请参阅逗号运算符:
When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.
当必须对一组表达式求值时,只考虑最右边的表达式。
回答by David Elliman
The comma operator evaluates the first expression and discards the result. Then it evaluates the second and that is what is the value tested in the if. You will find that your condition is not && nor || but behaves exactly like if(dst >= 0). Sometimes the form is useful for changing a value at the end of a loop before the test is carried out.
逗号运算符计算第一个表达式并丢弃结果。然后它评估第二个,这就是 if 中测试的值。你会发现你的条件不是 && 也不是 || 但行为与 if(dst >= 0) 完全一样。有时,该表单对于在执行测试之前在循环结束时更改值很有用。