Search code examples
cdivisionsubtractionsize-t

Is nel -= nel/2 functionally equivalent to nel /= 2?


I recently came across this chunk of code as part of the bsearch implementation from musl:

else if (sign < 0)
    nel /= 2;
else {
    base = try;
    nel -= nel/2;
}

nel is a size_t.

Is nel -= nel/2 functionally equivalent to nel /= 2?


Solution

  • You've self-answered correctly, but for this code in particular, after

    base = try;
    

    the first nel/2 items have been chopped off from further consideration. If you just did nel /= 2 at this point, and nel was odd, you'd also chop off the last item from further consideration, potentially producing false negatives.

    Note that the code you're looking at was recently changed to always chop off the item that was compared in the case of non-equality.