Back to Top

Tuesday, December 23, 2008

Modulo implies division!

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!

0 comments:

Post a Comment

You can use some HTML tags, such as <b>, <i>, <a>. Comments are moderated, so there will be a delay until the comment appears. However if you comment, I follow.