When you have a circular buffer represented as an array, and you need the index to wraparound (i.e., when you reach the highest possible index and increment it), is it “better” to:
return (++i == buffer.length) ? 0: i;
Or
return ++i % buffer.length;
Has using the modulo operator any drawbacks? Is it less readable than the first solution?
EDIT:
Of course it should be ++i instead of i++, changed that.
EDIT 2:
One interesting note: I found the first line of code in ArrayBlockingQueue’s implementation by Doug Lea.
The most readable version is the following:
Using
++adds unnecessary side effect to the check (not to mention that I strongly feel that you should’ve used pre-increment instead)What’s the problem with the original code? Let’s have a look, shall we?
So we know that:
iis post-incremented, so wheni == N-1before thereturnstatement, this will returnNinstead of wrapping to 0 immediatelyNas an exclusive upper boundisuggests a local variable by naming convention, but is it really?In comparison:
Here we know that:
iis not modified, doesn’t matter if it’s local variable or fieldi == N-1, the returned value is0, which is more typical scenarioThe
%approachAlternatively, you can also use the
%version as follows:What’s the problem with
%? Well, the problem is that even though most people think it’s the modulo operator, it’s NOT! It’s the remainder operator (JLS 15.17.3). A lot of people often get this confused. Here’s a classic example:That code is broken!!! It returns
falsefor all negative values! The problem is that-1 % 2 == -1, although mathematically-1 = 1 (mod 2).%can be tricky, and that’s why I recommend the ternary operator version instead. The most important part, though, is to remove the side-effect of the increment.See also