Friday, June 18, 2010

The % Operator in Java and C/C++

The % operator is colloquially called the mod or remainder operator, and most people assume that its behavior is the same in all languages. I mean, 8%5==3 in pretty much any language with a C-style syntax, including Java. But what if you have -8%3? Or, -8%-3? Or let's get really funky and what -8.03%-1.88 will be.

So here are the rules.
Both Java and C/C++ follow the ISO/IEC 1539:1991 standard, which maintains that (a/b)*b + a%b==a.

Hence, the % functions much more like a remainder operator than a modulus operator in mathematics. In addition, the ISO/IEC 1539:1991 standard states that quotients always round toward 0 when there are negative numbers invovled, which is why we sometimes end up with negative remainders.

The only difference between C/C++ and Java is that the % operator in Java accepts floats as arguments, while the C/C++ operator only accepts ints.