In accordance with the C ++ standard, section 5.6, paragraph 4:
The binary / operator gives the quotient, and the binary operator% gives the remainder of dividing the first expression by the second. If the second operand / or% is zero, the behavior is undefined; otherwise (a / b) * b + a% b is equal to a. If both operands are non-negative, then the remainder is non-negative; if not, the sign of the remainder is determined by the implementation.
The note suggests that rounding off quotient to zero should be preferred, leaving a negative balance.
Therefore, the approaches (end - start) % bufferSize do not work reliably. C ++ does not have modular arithmetic (except for the meaning suggested by unsigned integer types).
The approach recommended by j_random_hacker is different and looks good, but I do not know that this is a real improvement in simplicity or speed. Converting a boolean to int is inventive, but requires mental analysis, and that driving can be more expensive than using?:, Depending on the compiler and the machine.
I think that you have the simplest and best version, and I would not change it.
David thornley
source share