Konstantin K
Konstantin K

Reputation: 94

Preincrement in java

I have the following code fragment. No problem with it:

while (++left < to && less(a[left], a[from]));

where left is some array index, less(a, b) is helper function that returns true iff a <= b; a - array[from <= array index < to]

I particularly don't understand difference of the upper code from this:

 while (left < to && less(a[++left], a[from]));

As I have read, the preincreement evaluetes before the whole expression, but that is not the case (when i first used it I got the out of bound exception). Can someone, please, clarify this issue?

APPEND: Code for less:

private boolean less(T a, T b) {
        return a.compareTo(b) <= 0;
}

Upvotes: 1

Views: 97

Answers (2)

Abhishek Sinha
Abhishek Sinha

Reputation: 11

In the second snippet, first condition will evaluate to true upto max value of to - 1; which will cause second condition to evaluate with left value equal to to due to pre-increment. This is what may cause the index-out-of-bounds exception.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727097

One difference between the placement comes from not executing ++ when left equal to to-1: this means that ++left is equal to to, making < evaluate to false. This, in turn, leads to omitting the call to less(...) altogether due to short-circuiting of &&, thus preventing the exception.

When you move ++ into a[++left], you end up with one more iteration, which throws the out-of-bounds exception when left reaches to-1. After pre-incrementing, left becomes equal to to, which is out of bound for the array.

Upvotes: 1

Related Questions