2

Consider the following loop (in Swift - but my question is language independent):

    var index = standardizedTimeSpans.count - 1
    while index >= 0 && timeSpan < standardizedTimeSpans[index] {
        index--
    }
    index++ 

In the above code, the standardizedTimeSpans variable is an array of Doubles and the timeSpan variable is a Double.

The above loop may decrement the value of index down to a maximum of -1. If my conditional expression for the while statement was ordered the other way around (i.e. timeSpan < standardizedTimeSpans[index] && index >= 0), a runtime error would occur with array out of bounds in the event of the index reaching -1.

My question:

Is this code considered "safe"? In other words, is there a risk of a compiler change that doesn't necessarily sequence the evaluation of conditional from left to right? Of course, the alternative is to evaluate the conditions separately and but a break expression in the loop.

3 Answers3

2

"but my question is language independent"

It is of course language dependent. In any programming language where short circuit behaviour is part of the language definition, the code is "safe". Otherwise it is not.

Fortunately, any serious programming language of the C-based language families I know of has short circuit behaviour "by definition" (and lots of other programming languages, too). I do not know Swift, but since the inventors of that language were professionals, I am pretty sure they care for backwards compatibility. So I would not expect the behaviour to be changed in that language in the future.

Doc Brown
  • 218,378
0

I'm not sure about Swift specifically, but in general using the && operator short circuits and ends early if the left side is false. The code after the && will not be run.

Short circuiting is common practice in many languages.

0

my question is language independent

No, it isn't.

You are assuming that

  • the order of evaluation is well-defined
  • the order of evaluation is left-to-right
  • && is lazy in its right operand

All three of which are language-dependent. For example, in Visual Basic, And is strict in both its operands.

Jörg W Mittag
  • 104,619