Is it safe to access an array value in the stop condition of the loop?

arrays, c++, conditional-statements, loops, standards

Solution

The `&&` (logical and) operator always short circuits if it can. Your second example is safe.

Note, this applies to primitive types only, not those that overload the boolean operators.

Because no self-respecting `C++` answer would be complete without a standard quote:

5.14.1 (Logical AND) The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

5.14.2 (Logical OR) The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

Problem

To improve performance in my clique-partitioning program, which uses ordered arrays, I included in the stop condition of my `for` loop an access to an element of the array I'm looping into. ``` int myValue = 13; for (int i=0; array[i] < myValue; i++) { //performing operations on the array } ``` This is clearly unsafe, since it could be that my array only contains values that are less than `myValue`, so I tried this ``` int myValue = 13; for (int i=0; i < array.size() && array[i] < myValue; i++) { //performing operations on the array } ``` In this implementation, all seems to go well, but if I switch the conditions, I fall into the same problem of the first example. ``` int myValue = 13; for (int i=0; array[i] < myValue && i < array.size(); i++) { //performing operations on the array } ``` So, I deduced that this is clearly due to the way the compiler sets the order of the two conditions, since in the last case, even if I ask to enter the loop only if `i` is not greater than the size of the array, I'm previously reading a value that could be out of the bounds of the array. My question is: is it always safe to do as I did in the second implementation, or could the compiler sometimes switch my control conditions leading to unsafe code? Thanks.

Original source