C++: Multiple exit conditions in for loop (multiple variables): AND -ed or OR -ed?

戏子无情 提交于 2021-02-06 14:52:32

问题


For loops and multiple variables and conditions.

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];
}

Something like that anyway.

(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 (||).

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.


回答1:


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.

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.




回答2:


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.



来源:https://stackoverflow.com/questions/18063552/c-multiple-exit-conditions-in-for-loop-multiple-variables-and-ed-or-or-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!