To improve the performance of my clique-partitioning program, which uses ordered arrays, I included access to the element of the array that I am looping in to stop my for loop.
int myValue = 13; for (int i=0; array[i] < myValue; i++) {
This is clearly unsafe, as it may be that my array contains only myValue values, so I tried this
int myValue = 13; for (int i=0; i < array.size() && array[i] < myValue; i++) {
Everything seems to be going well in this implementation, but if I switch the conditions, I will fall into the same problem of the first example.
int myValue = 13; for (int i=0; array[i] < myValue && i < array.size(); i++) {
So, I realized that this is clearly due to the way the compiler sets the order of the two conditions, because in the latter case, even if I ask to enter a loop only if i not larger than the size from the array, I first read the value, which may be outside the bounds array.
My question is: is it always safe to do what I did in the second implementation, or can the compiler sometimes switch my control conditions, resulting in unsafe code?
Thanks.
source share