C ++:for循环中有多个退出条件(多个变量):AND -ed或OR -ed? [英] C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?

查看:70
本文介绍了C ++:for循环中有多个退出条件(多个变量):AND -ed或OR -ed?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用for循环来设置源索引和目标索引以复制数组中的项目.

I am using a for loop to set source and destination indexes to copy items in an array.

for(int src = 0, dst = 8;
    src < 8, dst >= 0;
    src ++, dst --)
{
    arr2[dst] = arr1[src];
}

反正就是这样.

我的问题是关于退出条件.这里有两个. src<8 dst> = 0 .这些条件是与"(&& )还是或"( || ).

My question is about the exit conditions. There are two here. src < 8 and dst >= 0. Are these conditions AND-ed (&&) or OR-ed (||).

为进一步说明,是否对条件进行了这样的评估:

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.

推荐答案

逗号运算符将返回正确表达式的值,因此编写如下:

The comma operator will return the value of the right expression, so writing this:

 src < 8, dst >= 0;

作为条件,这与仅写入 dst> = 0 相同. src<在这种情况下,8 将被完全忽略,因为它是与第二个条件分开评估的,然后返回第二个条件.这并不等于AND或OR,但实际上只是完全扔掉"了第一张支票.

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.

如果要正确评估,则应使用两个选项之一(通过 || &&明确指定行为).

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.

这篇关于C ++:for循环中有多个退出条件(多个变量):AND -ed或OR -ed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆