When programming, if you write
foo / bar, where foo and bar are variables, you usually instinctively thing “can bar be zero? do I need to add a check that bar is zero?”. However how many of you apply the same line of thinking to the modulo operator? I didn’t (until now – when it bit me :-)).
However it is logical that doing
foo % 0 gives you a division by zero error. First of all, the modulo (remainder) operator is defined using division:
In computing, the modulo operation finds the remainder of division of one number by another.
The relation is so close that for x86 machine code there is not instruction to calculate the remainder. You have to use the DIV instruction, which puts in one register the result of the division and in an other register the remainder. This gives an other reason why the modulo operator results in a division by zero error.
So the next time you see
foo % bar, think about bar!