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.
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: