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

前端 未结 2 1218
甜味超标
甜味超标 2021-02-12 13:31

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,          


        
2条回答
  •  日久生厌
    2021-02-12 13:48

    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.

提交回复
热议问题